Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 132 ยท State and Events

State with useState

Understand React state with useState - why plain variables fail, the snapshot model, lazy initial values, multiple state variables, state per component instance and resetting state with a key.

A component renders from its props. But a real interface also remembers things: whether a menu is open, what the user typed, which tab is selected, how many items are in a cart. Props cannot hold that memory, because props come from the parent and the component may not change them. React's answer is state: data that belongs to one component instance, survives between renders, and causes React to render again when it changes.

The tool for adding state to a function component is the useState hook. This lesson starts with why an ordinary variable is not enough, explains the one idea that makes state click (state is a snapshot), and then covers initial values, multiple state variables, state that belongs to each component instance, and how to reset it with a key.

Why a normal variable is not enough

Try the obvious thing first: keep a count in a variable and change it in a click handler.

A plain variable does not update the screen (fails on purpose)

Click the button a few times. The console says count is now 1, 2, 3, yet the label stays at "Clicked 0 times". Two things go wrong at once:

  1. Local variables do not persist. Each time React renders BrokenCounter, it calls the function again from the top, and let count = 0 starts over.
  2. Changing a local variable does not trigger a render. React has no idea that count changed, so it never calls the component again.

We need something that (1) is kept by React between renders and (2) tells React "render again" when it changes. That is exactly what useState provides.

The useState hook

JSX
const [count, setCount] = useState(0);

useState takes the initial value and returns a two-item array: the current state value and a setter function. We name them with array destructuring, by convention [something, setSomething].

A counter with useState

Here is what happens, step by step:

  1. First render. React calls Counter(). useState(0) sees this is the first time, stores 0 in a slot that belongs to this component instance, and returns [0, setCount]. The JSX shows "Clicked 0 times".
  2. You click. The handler calls setCount(1). React does not change count in the running code. It records "the next value is 1" and schedules a new render.
  3. Second render. React calls Counter() again. This time useState(0) ignores its argument (the initial value is used only once) and returns the stored [1, setCount]. The JSX shows "Clicked 1 times".
  4. React compares the new output with the old one and updates only the text node in the real DOM.

The console shows render, count = 0 once, then render, count = 1 after the first click, and so on: one line per render. The name "hook" comes from the fact that useState hooks into React's internal memory for this component.

State is private to the component instance

State is not shared. If you render <Counter /> twice, each has its own memory.

Each instance has its own state

Click "Photos" a few times: only its counter moves. React ties each hook's data to the position of the component in the tree. Same component type, different position, separate state. This is why state is described as "local" or "encapsulated", and why sharing it requires lifting it up.

State is a snapshot

This is the key idea of the whole lesson. When React renders your component, it hands you a snapshot of the state for that render. Every value you see in the function body, including inside event handlers created during that render, is fixed for that render. Calling the setter does not change the variable you already have; it asks for the next render with a new value.

The snapshot: set, then read

Click once. The console shows before set: count = 0, right after set: count = 0 and, 200 ms later, 200 ms later, in the same handler: count = 0, while the screen shows 1. All three lines read the same count because the handler is a closure over the snapshot of the render in which it was created: that render's count is 0, forever. The screen shows 1 because React already rendered again with a new snapshot in which count is 1, and a fresh handler.

Think of each render as a photograph: the picture of render 0 will always show count = 0, even after you have taken picture 1. This explains many "bugs" that are not bugs, such as a timeout that "uses an old value". How State Updates Work shows how to deal with it when you need the latest value.

Setting state triggers a render, not a mutation

Three properties of the setter are worth memorizing:

  • Calling it asks React to re-render. If the new value is the same as the current one (compared with Object.is), React skips the work.
  • Never assign to the state variable. count = count + 1 or count++ changes nothing React tracks. Always go through the setter.
  • The setter does not return the new value and does not update the variable synchronously, as the snapshot demo showed.

Updates from the same event are also batched into one render; see the next lesson.

The initial value and lazy initialization

The argument to useState is only used on the first render. After that it is ignored. That has a catch: if you compute the initial value by calling an expensive function, useState(expensive()) still calls expensive() on every render, even though the result is thrown away.

To avoid that, pass a function; React calls it only during the first render (a "lazy initializer").

Lazy initial state

On the first render the console shows buildItems() called twice, once for each component. Click "re-render" in Eager and the function is called again each time; click it in Lazy and there is no new log. Note the difference in the code: useState(buildItems()) passes the result; useState(buildItems) passes the function itself. This is the same mistake as onClick={handler()} from the events lesson. Use the lazy form whenever the initial value requires real work, such as reading and parsing data or building a large array. For a literal like 0 or '', there is no need.

Several state variables

A component can call useState as many times as it likes. React matches each call with its slot by call order, which is why hooks must always be called in the same order (see Rules of Hooks).

Multiple state variables

Use separate variables when pieces of state change independently. If two values always change together (say x and y of a pointer position), keep them in one object instead; the trade-offs are discussed in Choosing a State Structure.

State can hold any JavaScript value: numbers, strings, booleans, objects, arrays, even null. Objects and arrays have special rules, covered in Objects and Arrays in State.

What should be state?

Not every changing value belongs in state. A quick filter:

  • If a value can be computed from props or other state, calculate it during render instead (const total = price * quantity). Do not store it.
  • If a value changes but should not cause a render (a timer id, a previous value for comparison), use a ref; see useRef.
  • If a value is the same for the lifetime of the component, it is a constant, not state.

Everything else, meaning data that changes over time because of user actions or incoming events and that is shown on screen, is state.

Resetting state with a key

React keeps state as long as the component stays at the same position in the tree with the same type. Switch to different content at that position and it is thrown away. You can use this on purpose with the special key prop: giving a component a different key makes React treat it as a brand-new instance and reset its state.

Reset state by changing the key

Type something into both inputs, then switch from Ada to Grace. The first draft is kept (a draft meant for Ada is now headed to Grace, which is probably a bug), while the keyed one starts empty again because Ada's instance was unmounted and a new one for Grace was mounted. This technique is cleaner than writing an effect that clears state when a prop changes; it is explored further in You Might Not Need an Effect and Reconciliation and Keys in Depth.

Common pitfalls

  • Mutating state directly. items.push(x) followed by setItems(items) does not work: it is the same array, so React sees no change.
  • Expecting the new value right after the setter. It is a snapshot; use the value you passed (const next = count + 1; setCount(next); use(next)).
  • Calling the setter during render. setCount(count + 1) in the body of the component causes an infinite loop. Set state in event handlers and effects only.
  • Copying props into state. useState(props.color) only reads the prop once. If you need the live value, use the prop directly.
  • Too much state. Derive what you can; keep the minimal set.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does a local variable (let count = 0) fail as a counter in a component?

    The component function runs again for each render, so a local variable starts over, and React is never told that it changed.
  2. 2. In a click handler you call setCount(count + 1) and then console.log(count). What is logged if count was 5?

    State is a snapshot. The variable count holds 5 for the whole render in which the handler was created; the new value 6 only appears in the next render.
  3. 3. What is the difference between useState(compute()) and useState(compute)?

    Passing the function lets React call it lazily during the first render only. Passing the call result evaluates it on every render and discards it after the first.
  4. 4. Two instances of the same component are rendered side by side. How is their state related?

    State is tied to the position of a component in the tree, so every instance has private state.
  5. 5. How can you reset a component's state when a prop such as userId changes?

    A different key makes React unmount the old instance and mount a new one, which starts with fresh initial state.

Summary

  • State is memory that React keeps for a component instance between renders; changing it schedules a new render.
  • const [value, setValue] = useState(initial) returns the current value and a setter; the initial value is only used on the first render.
  • State is a snapshot: inside one render (and its handlers) the value never changes, even after you call the setter.
  • Pass a function (useState(init)) to compute an expensive initial value lazily.
  • You can use many useState calls; each instance of a component has its own state.
  • Do not store derived values in state, never mutate state directly, and never call a setter during render.
  • Change the key to reset a component's state.

Next: How State Updates Work