TExcelTAD
Home › React › React ES6 Refresher

React ES6 Refresher

React code is modern JavaScript. You'll read and write the same handful of ES6+ features in every component, so this lesson recaps them with short runnable examples. If you already know them, skim the table and jump to the quiz.

Feature Looks like Used in React for
const / let const [a, setA] = … almost every variable
Arrow functions (x) => x * 2 event handlers, .map callbacks
Destructuring function Card({ title }) props and useState results
Spread { ...user, name }, [...list, item] immutable state updates
Template literals `Hello ${name}` building strings and class names
Array methods .map, .filter, .find rendering and editing lists
Ternary / && ok ? a : b conditional rendering
Modules import / export splitting components into files
Promises / async await fetch(…) loading data

Arrow functions

Arrow functions are short function expressions. With a single expression body, the value is returned automatically:

js · try it yourself
const double = (n) => n * 2;
const greet = (name) => `Hi, ${name}!`;
const makeUser = (name) => ({ name, admin: false }); // wrap objects in ()

console.log(double(21));
console.log(greet('Ana'));
console.log(makeUser('Ben'));
42
Hi, Ana!
{ name: 'Ben', admin: false }

Destructuring

Pull values out of objects and arrays by name or position. React uses both forms constantly: function Card({ title }) destructures props, and const [count, setCount] = useState(0) destructures an array.

js · try it yourself
const props = { title: 'Inbox', unread: 3, color: 'blue' };
const { title, unread, size = 'medium' } = props;
console.log(title, unread, size);

const pair = ['value', () => 'setter'];
const [value, setValue] = pair;
console.log(value, typeof setValue);

const { color, ...rest } = props;
console.log(color, rest);
Inbox 3 medium
value function
blue { title: 'Inbox', unread: 3 }

Spread: copying with changes

State must never be mutated in React, so you constantly create updated copies. The spread operator ... makes this easy:

js · try it yourself
const todo = { id: 1, text: 'Learn JSX', done: false };
const updated = { ...todo, done: true };

console.log(todo.done, updated.done);

const list = [1, 2, 3];
const added = [...list, 4];
const removed = list.filter((n) => n !== 2);
const doubled = list.map((n) => n * 2);
console.log(list, added, removed, doubled);
false true
[ 1, 2, 3 ] [ 1, 2, 3, 4 ] [ 1, 3 ] [ 2, 4, 6 ]

Note: Spread copies only one level deep. For nested objects, spread each level you change: { ...user, address: { ...user.address, city: 'Hue' } }.

Array methods

map transforms every item, filter keeps some, find returns the first match and reduce combines items into one value. None of them modify the original array:

js · try it yourself
const products = [
  { name: 'Pen', price: 2, inStock: true },
  { name: 'Notebook', price: 5, inStock: false },
  { name: 'Bag', price: 30, inStock: true },
];

console.log(products.map((p) => p.name));
console.log(products.filter((p) => p.inStock).length);
console.log(products.find((p) => p.price > 4).name);
console.log(products.reduce((sum, p) => sum + p.price, 0));
[ 'Pen', 'Notebook', 'Bag' ]
2
Notebook
37

Conditional expressions

JSX can only contain expressions, not if statements, so the ternary operator and logical && / ?? are everywhere:

js
const unread = 0;
const user = null;

unread > 0 ? `${unread} new` : 'No new mail';   // 'No new mail'
unread > 0 && 'has mail';                       // false (renders nothing in JSX)
user?.name ?? 'Guest';                          // 'Guest'

?. (optional chaining) stops at null/undefined instead of throwing, and ?? provides a fallback only for null/undefined.

Modules

Each component usually lives in its own file and is shared with export/import:

js
// Button.jsx
export default function Button() { /* … */ }   // default export: one per file
export const SIZES = ['sm', 'md', 'lg'];        // named export

// App.jsx
import Button, { SIZES } from './Button.jsx';

Promises and async/await

Loading data is asynchronous. async functions return a Promise, and await pauses until it settles:

js · try it yourself
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

async function loadUser(id) {
  await wait(100);
  if (id < 1) throw new Error('Invalid id');
  return { id, name: 'Mai' };
}

const user = await loadUser(7);
console.log(user.name);

try {
  await loadUser(0);
} catch (err) {
  console.log('Failed:', err.message);
}
Mai
Failed: Invalid id

Test yourself

What does const { a, ...rest } = { a: 1, b: 2, c: 3 } put in rest?

  1. [2, 3]
  2. { b: 2, c: 3 }
  3. { a: 1, b: 2, c: 3 }
  4. undefined

Which expression creates a copy of todo with done set to true, without changing todo?

  1. todo.done = true
  2. Object.freeze(todo)
  3. { ...todo, done: true }
  4. [...todo, true]

What does null ?? 'Guest' evaluate to?

  1. null
  2. 'Guest'
  3. false
  4. It throws