Skip to the content

Lesson 160 of 296

State and useState

What you will learn

  • What state is
  • The useState hook
  • Why setting state causes a re-render
  • State as a snapshot
  • Functional updates
  • Batching
  • Updating objects and arrays immutably
  • Lazy initial state
On this page

What is state?

State is data that belongs to a component and can change over time, such as the text in a search box, whether a menu is open, or items in a basket. When state changes, React re-renders the component so the screen matches.

Normal variables do not work for this:

function Counter() {
  let count = 0;
  return <button onClick={() => count++}>{count}</button>;
}

Clicking changes count, but React does not know, so the screen never updates. And every render runs the function again from the top, so count is reset to 0 anyway.

useState

A hook is a special function starting with use that lets a component use React features. useState gives a component a state value that survives between renders, and a function to change it.

TSX
import { useState } from "react";

function Counter() {
  const [count, setCount] = useState(0);
  return (
    <button type="button" onClick={() => setCount(count + 1)}>
      Clicked {count} times
    </button>
  );
}
  • useState(0): the initial value, used only on the first render.
  • It returns a pair (a tuple, Lesson 101): the current value and a setter function. We destructure it (Lesson 62).
  • Calling setCount(...) stores the new value and schedules a re-render. On the next render, count has the new value.

State is a snapshot

Inside one render, a state variable never changes. Setting state does not change the variable you already have; it asks for a new render with the new value.

TSX
function SnapshotDemo() {
  const [count, setCount] = useState(0);
  function handleClick() {
    setCount(count + 1);
    setCount(count + 1);
    setCount(count + 1);
    console.log(count);
  }
  return <button type="button" onClick={handleClick}>{count}</button>;
}

Clicking once logs 0 and the count becomes 1, not 3. All three calls used the same snapshot value count = 0, so each asked for 0 + 1.

Functional updates

When the new state depends on the previous state, pass a function. React calls it with the latest value:

TSX
function TripleCounter() {
  const [count, setCount] = useState(0);
  function addThree() {
    setCount((c) => c + 1);
    setCount((c) => c + 1);
    setCount((c) => c + 1);
  }
  return <button type="button" onClick={addThree}>{count}</button>;
}

Now one click adds 3. Rule: use the function form whenever the next value is calculated from the current one. It also avoids stale values in timers and async code (Lesson 170).

Batching

React groups several state updates in the same event (and, since React 18, in timeouts and promises too) into one re-render. This is called batching and makes updates efficient.

Objects and arrays: update immutably

React decides whether state changed by comparing the old and new value with Object.is (Lesson 47). If you mutate an object and set the same object, React sees the same reference and may not re-render.

user.name = "Ali";
setUser(user);          same object: React may skip the update

Always create a new object or array (Lesson 48):

TSX
type User = { name: string; email: string };

function UserForm() {
  const [user, setUser] = useState<User>({ name: "", email: "" });
  const [tags, setTags] = useState<string[]>([]);

  const rename = (name: string) => setUser((u) => ({ ...u, name }));
  const addTag = (tag: string) => setTags((t) => [...t, tag]);
  const removeTag = (tag: string) => setTags((t) => t.filter((x) => x !== tag));

  return (
    <div>
      <input value={user.name} onChange={(e) => rename(e.target.value)} />
      <button type="button" onClick={() => addTag("new")}>Add tag</button>
      <button type="button" onClick={() => removeTag("new")}>Remove tag</button>
      <p>{tags.join(", ")}</p>
    </div>
  );
}
ChangeImmutable way
Add to array[...arr, item]
Remove from arrayarr.filter(...)
Change one itemarr.map((x) => (x.id === id ? { ...x, done: true } : x))
Update a property{ ...obj, key: value }
Update nested dataCopy each level you change: { ...order, address: { ...order.address, city } }

Lazy initial state

If the initial value is expensive to calculate (for example reading and parsing localStorage), pass a function, so it only runs on the first render:

TSX
function SavedNotes() {
  const [notes, setNotes] = useState<string[]>(() => {
    try {
      return JSON.parse(localStorage.getItem("notes") ?? "[]") as string[];
    } catch {
      return [];
    }
  });
  return <p onClick={() => setNotes([])}>{notes.length} notes</p>;
}

useState(expensive()) would call expensive() on every render and throw the result away.

What should be state?

Keep state minimal. Do not store values you can calculate from other state or props during rendering:

const [items, setItems] = useState<Item[]>([]);
const [count, setCount] = useState(0);      unnecessary: use items.length

Duplicated state gets out of sync. Calculate it instead: const count = items.length;.

How to say it in an interview

"State is component data that changes over time; useState returns the current value and a setter, and calling the setter schedules a re-render. Within a render, state is a snapshot, so three setCount(count plus 1) calls in one handler only add one; when the next value depends on the previous I use the functional form. React batches updates into one render and compares state with Object.is, so I always update objects and arrays immutably. I keep state minimal and derive anything I can calculate."

Key words

WordMeaning
StateComponent data that changes over time
HookA special use... function that gives components React features
useStateThe hook that stores state and returns a setter
Re-renderReact calling the component again to get new UI
SnapshotState values are fixed within one render
Functional updatesetX((prev) => ...)
BatchingGrouping several updates into one render
Derived valueA value calculated from state instead of stored

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.