ReactEasy

What is useState?

useState adds a state variable to a function component. const [value, setValue] = useState(initial) returns the current value and a setter; calling the setter with a new value schedules a re-render in which value is the new value.

Signature

  • useState(initialValue) or useState(() => computeInitial()) for lazy initialization (runs only on the first render).
  • Returns [state, setState]. The setter's identity is stable across renders, so it is safe to omit from dependency arrays.

Updating

  • setValue(next) replaces the value.
  • setValue((prev) => next) when it depends on the previous value.
  • Objects and arrays must be replaced with new copies; mutations are not detected.
  • Setting a value equal to the current one (by Object.is) skips the re-render.

Snapshot behavior

Each render sees its own constant value. After calling the setter, the variable in the current scope does not change; the next render receives the new value.

Choosing what to store

  • Store the minimal data; derive the rest during render.
  • Several useState calls for unrelated values, or one object for values that change together.
  • Switch to useReducer when updates follow complex rules or many fields change together.

TypeScript

Infers from the initial value; specify when it starts empty: useState<User | null>(null).

Code example

tsx
1import { useState } from "react";
2
3type User = { id: string; name: string };
4
5export function Profile() {
6 const [count, setCount] = useState(0);
7 const [user, setUser] = useState<User | null>(null);
8 const [draft, setDraft] = useState(() => localStorage.getItem("draft") ?? ""); // lazy init
9
10 return (
11 <div>
12 <button onClick={() => setCount((c) => c + 1)}>Clicked {count} times</button>
13
14 <button onClick={() => setUser({ id: "1", name: "Ada" })}>Load user</button>
15 {user && <p>Hello {user.name}</p>}
16
17 <textarea
18 value={draft}
19 onChange={(e) => {
20 setDraft(e.target.value);
21 localStorage.setItem("draft", e.target.value);
22 }}
23 />
24 </div>
25 );
26}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app