State: a component's memory

Intermediate

Introduction

Components so far show what their props say. Real interfaces change: a counter goes up, a menu opens, a form fills in. A component needs to remember things between renders, and React needs to know when they change so it can update the page. That memory is state, and the useState Hook is how you get it.

How it works

useState takes the starting value and returns two things, which you name with array destructuring:

import { useState } from "react";

function Counter() {
  const [count, setCount] = useState(0);
  return <button onClick={() => setCount(count + 1)}>Clicked {count} times</button>;
}

count is the current value; setCount changes it and tells React to render the component again. That second part is why a normal variable does not work: let count = 0; count++ changes the variable, but React does not know, and the next render starts from 0 again anyway, because the function runs from the top.

Functions whose names start with use are Hooks. Call them only at the top level of a component, never inside conditions or loops, because React matches each useState call to its value by the order of the calls.

Each render sees a snapshot of the state. Inside a click handler, count is the value from the render the button belongs to, and calling setCount(count + 1) twice in a row sets it to the same value twice. When the next value depends on the previous one, pass an updater function: setCount((c) => c + 1). React calls it with the latest value, so two updaters add two.

A component can have several state variables, each with its own useState. State is private to each copy of a component: two <Counter /> elements count separately.

Objects and arrays in state must be treated as immutable: never change them in place, because React compares the old and new values to decide whether to render, and a changed-in-place object looks the same. Make a new one instead: setUser({ ...user, name: "Ada" }), setItems([...items, newItem]), setItems(items.filter((i) => i.id !== id)), setItems(items.map((i) => (i.id === id ? { ...i, done: true } : i))).

Example

App.jsx
console.log output from the page shows here.

Line by line

  1. Two state variables: count starts at 0, step at 1.
  2. "Add" adds the current step; "Use step" switches the step between 1 and 10.
  3. "Add 2 with updaters" calls the setter twice with updater functions, so both additions count.
  4. "Reset" sets the count back to 0. Every setter call makes React render App again with the new values.

Expected result

The preview starts at "Count: 0". Pressing "Add 1", then "Use step 10", then "Add 10" shows "Count: 11"; "Add 2 with updaters" then shows 13, and "Reset" goes back to 0.

In the real world

Everything that changes in an interface is state somewhere: whether a dropdown is open, the text in a search box, the selected tab, the items in a cart, the current page of results. Deciding what is state, and which component owns it, is the central design question in React apps, and the next lessons are about exactly that.

Common mistakes

  • Changing a variable or the state object directly, so React never renders again.
  • Calling a Hook inside an if or a loop, which breaks the order React relies on.
  • Expecting state to change immediately after calling the setter: the new value arrives in the next render.
  • Calling a setter during render, which renders again forever.

Best practices

  • Keep the minimum state; compute everything else from it during render.
  • Use updater functions when the new value depends on the old one.
  • Make new objects and arrays with spread, map and filter instead of changing them.

Summary

useState gives a component a state variable and a setter. Calling the setter stores a new value and makes React render the component again; within one render, state is a fixed snapshot, so updater functions are used when the next value depends on the previous one. State objects and arrays are replaced, never changed in place, and Hooks are called only at the top level.

Quick check

1. Why can a normal let variable not drive a counter?
2. count is 0. What is it after setCount(count + 1); setCount(count + 1);?
3. How do you add an item to an array in state?
4. Where may useState be called?

Key takeaways

  • const [value, setValue] = useState(initial) gives a component memory; calling setValue renders it again.
  • Within one render the state is a fixed snapshot; use c => c + 1 when the new value depends on the old.
  • Never modify state objects or arrays; make new ones with spread, map and filter.

Practice problems for this lesson

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.