Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 132 ยท Getting Started

The JavaScript You Need for React

A focused JavaScript refresher for React learners - destructuring, spread and rest, arrow functions, map/filter/reduce, optional chaining, modules, closures, async and immutability.

React is not a new language. It is JavaScript with a few conventions, which means that most of what makes React code look unusual is ordinary modern JavaScript that you may not have used much yet: destructured parameters, spread syntax, arrow functions and .map() chains. If these feel shaky, React will feel harder than it is.

This lesson is a tour of exactly the language features that React code uses every day, each shown in a React setting so you see why it matters. It is not a full JavaScript course. When you want the long version of any topic, follow the links to the JavaScript tutorial. If you are already comfortable with all of these, skim the section headings and the summary, then move on to Your First Components.

Destructuring

Destructuring unpacks values from objects and arrays into variables. React uses it constantly, in two places in particular: the parameters of a component (props) and the result of useState.

JavaScript
const person = { name: 'Ada', age: 36, city: 'London' };

const { name, age } = person;        // object: match by property name
const { city: town = 'Unknown' } = person;  // rename + default value

const [first, second] = ['a', 'b', 'c'];     // array: match by position

Object destructuring matches names, array destructuring matches positions. That is why const [count, setCount] = useState(0) lets you choose any names, while props must use the names the parent passed. More in Destructuring.

Destructuring in a function parameter keeps component signatures short and documents the props:

JSX
// Instead of function Card(props) { ... props.title ... props.price ... }
function Card({ title, price = 0, tags = [] }) {
  /* ... */
}

Spread and rest

The three dots do two opposite jobs depending on where they appear.

  • Spread (in an expression) expands an array or object into pieces: [...list, 4], { ...user, age: 37 }.
  • Rest (in a pattern or parameter list) gathers the remaining pieces: const { id, ...others } = item, function f(first, ...more).

Both create new arrays and objects instead of changing existing ones, which React needs for state updates (see the immutability section below). Details: Spread and Rest.

Destructuring, spread and rest in components

{ ...product, price: ... } copies the object and replaces one property, leaving product untouched (the first log still shows 4.5). aria-label is not a named prop of Card, so it falls into ...rest and is forwarded to the div.

Arrow functions and callbacks

An arrow function is a compact way to write a function. In React you mostly meet it as an inline callback, a function you pass somewhere else: an event handler, a .map callback, an updater.

JavaScript
const add = (a, b) => a + b;          // expression body: returns the value
const square = (n) => n * n;          // one parameter
const make = () => ({ ok: true });    // wrap an object literal in parentheses
const log = (x) => {                  // block body: needs an explicit return
  console.log(x);
  return x;
};

Two reminders: an arrow function without braces returns its expression, and returning an object literal needs parentheses so that the braces are not read as a block. Also, passing a function is different from calling it:

JSX
<button onClick={handleSave}>Save</button>         {/* passes the function */}
<button onClick={() => remove(id)}>Delete</button>  {/* wraps a call with an argument */}
<button onClick={remove(id)}>Delete</button>        {/* BUG: calls remove during render */}

See Arrow Functions.

Array methods: map, filter, reduce

React has no template loops. You turn data into UI with array methods that return new arrays:

  • map transforms each element, and is how you produce lists of elements.
  • filter keeps the elements that pass a test.
  • reduce folds an array into a single value.
  • find, some, every, includes answer questions about an array.
  • sort reorders in place, so copy first: [...items].sort(...) or items.toSorted(...).
map, filter and reduce build the UI

Notice that every list in JSX has a key taken from the data (order.id). Learn the array methods well: nearly every screen in a React app ends in a .map. More in Array Methods.

Template literals

Backticks give you multi-line strings and ${expression} interpolation. They are handy for class names, labels and messages:

JSX
const label = `${count} ${count === 1 ? 'item' : 'items'} in cart`;
const className = `btn ${isActive ? 'btn-active' : ''}`.trim();

In JSX a template literal goes inside braces like any expression, but often it is simpler to write the pieces as text and braces: <p>Hello, {name}</p>. See Template Literals.

Optional chaining and nullish coalescing

Real data is often missing: a user who has not loaded yet, an optional field. Two operators make that safe to read:

  • a?.b returns undefined instead of throwing when a is null or undefined. It also works for calls (fn?.()) and indexes (list?.[0]).
  • a ?? fallback uses the fallback only when a is null or undefined. Compare with a || fallback, which also replaces 0 and "".
Safe reads with ?. and ??

Linus has address: null, so user.address.city would crash with a TypeError; user.address?.city is undefined, and ?? supplies the text. Ada's score of 0 is real: ?? keeps it, || wrongly replaces it with "n/a". Prefer ?? for defaults. See Nullish Coalescing and Optional Chaining.

Modules: import and export

In a real project every file is a module. You share things with export and use them with import:

JavaScript
// Badge.jsx
export default function Badge({ label }) {   // default export: one per file
  return <span>{label}</span>;
}
export const colors = ['red', 'blue'];       // named export: as many as you like

// App.jsx
import Badge, { colors } from './Badge.jsx'; // default (any name), then { named }
import { useState } from 'react';            // from a package (no ./ path)

The rules of thumb: a default import can be given any local name; a named import must match the exported name (or be renamed with as). A path that starts with ./ or ../ is your own file; a bare name such as 'react' comes from node_modules. Our editor examples use a single file, so they only import from react and react-dom/client. The block above is read-only, because the editor cannot import other files. See JavaScript Modules.

Closures

A function remembers the variables that were around when it was created. This is called a closure, and it is why event handlers can read props and state. It is also the source of React's classic "stale value" surprises, which you will meet in State Updates and Effect Dependencies.

Every render of a component creates new variables and new inner functions. A handler created in render number 3 remembers the values of render 3, forever.

Closures remember their own render

Each makeCounter call makes its own private count, so apples and pears count separately. The same mechanism is at work when a component function runs again with new props: new variables, new closures. See Closures.

Promises and async/await

Anything slow, such as a network request or a timer, is asynchronous: you start it and get the result later. A Promise represents that future result. async/await lets you write the waiting code in a straight line:

JavaScript
async function loadUser(id) {
  try {
    const response = await fetch(`/api/users/${id}`);   // read-only: needs a server
    if (!response.ok) throw new Error('HTTP ' + response.status);
    return await response.json();
  } catch (error) {
    console.error('Could not load', error);
    return null;
  }
}

An async function always returns a promise, await pauses that function (not the page) until the promise settles, and try/catch handles failures. The next example uses a made-up loadUser that waits a short time with setTimeout, because the sandboxed editor has no server to call. In a component, you start the work from an event handler and store the result in state.

async and await in a click handler

Press each button: the first shows "loading" and then "Loaded User #1"; the second ends with the error message. This pattern (status in state, await in a handler or an effect, try/catch) is the foundation of Fetching Data. See also Promises and async/await.

Immutability basics

The last idea is the most important for React. Do not change objects and arrays that are in state; build new ones. React decides whether something changed by comparing references (Object.is), so mutating an object in place gives it the same reference and React may not update the screen.

Goal Mutates (avoid with state) Returns new (use this)
Add to array push, unshift [...list, item]
Remove splice, pop list.filter(...)
Replace one list[i] = x list.map(...)
Sort sort, reverse [...list].sort(...) or toSorted
Update a field obj.a = 1 { ...obj, a: 1 }
New reference versus mutation

Click Mutate a couple of times: the console reports a growing length but the screen still shows "a, b", because React was never told anything changed. Click Re-render only and the screen suddenly catches up with the mutated array, which proves the data had changed behind React's back; relying on accidental re-renders is a bug waiting to happen. Replace state does it properly: a new array and setList. Objects and Arrays in State covers this in depth, and Copying Objects explains shallow versus deep copies.

Spread makes a shallow copy: nested objects are still shared. To change user.address.city you copy each level on the path: { ...user, address: { ...user.address, city: 'Paris' } }.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does const { name, ...others } = item do?

    Object destructuring with a rest element picks out named properties and collects everything else into a new object, leaving item unchanged.
  2. 2. Why does the screen not update after list.push('x') on an array held in state?

    React compares references. Mutating in place keeps the same reference and never calls the setter, so React does not re-render. Create a new array and pass it to the setter.
  3. 3. For a user with score: 0, what do user.score ?? 'n/a' and user.score || 'n/a' return?

    ?? replaces only null and undefined, so a real 0 is kept. || replaces every falsy value, including 0 and the empty string.
  4. 4. What is wrong with onClick={remove(id)}?

    remove(id) is evaluated immediately. Pass a function instead, for example onClick={() => remove(id)}.
  5. 5. Which array method should you avoid calling directly on an array that is in state?

    sort (like push, splice and reverse) mutates the array it is called on. Copy first with [...items].sort(...) or use toSorted.

Summary

  • Destructuring unpacks props and useState results; spread copies and extends arrays and objects, and rest gathers the remainder.
  • Arrow functions are the usual form for callbacks; pass functions to handlers, do not call them in the JSX.
  • map, filter and reduce turn data into UI; copy before sort.
  • Use ?. to read possibly missing values and ?? for defaults that keep 0 and "".
  • Files are modules: export what others need, import what you use. Our editors use a single file.
  • Closures let a function remember the variables of the render that created it.
  • async/await with try/catch handles asynchronous work; the result goes into state.
  • Never mutate state objects or arrays; create new ones.

Next: Your First Components