Skip to content

Lesson 7 of 37State

useState

Give components memory with useState, and understand exactly when and why React re-renders.

14 min read0/4 questions

Everything interactive in React (a counter, a form, an open menu, a selected tab) is state: data a component remembers that can change while the user interacts with it. You have been using useState in demos already. This lesson explains what it actually does, which is the foundation for every hook and every "why didn't my screen update?" bug you will debug.

Why a normal variable does not work

Here is a counter written with a plain let. Click the button a few times and watch the log below the preview.

React
export default function App() { let count = 0; function handleClick() { count = count + 1; console.log("count is now", count); } return <button onClick={handleClick}>Clicked {count} times</button>;}

The log goes 1, 2, 3, but the button stays at 0. Two separate things are wrong:

  1. Changing a local variable does not tell React anything. React has no idea it should re-render, so the screen never updates.
  2. Local variables do not survive a re-render. Even if something else caused a re-render, React would call App() again, which runs let count = 0 again from scratch.

State fixes both: it is a value React stores for you between renders, and changing it through a setter triggers a re-render.

Quick check
A teammate moves let count = 0 outside the component (to module level) so it survives. The log works, but what is still wrong?
Need a nudge? A hint rules out a wrong answer.

useState: a value plus a setter

React
import { useState } from "react"; export default function App() { const [count, setCount] = useState(0); return ( <button onClick={() => setCount(count + 1)}> Clicked {count} times </button> );}

useState(0) returns an array of exactly two things, which you name with array destructuring:

  • count: the current value for this render. On the first render it is the initial value, 0.
  • setCount: a function that stores a new value and asks React to re-render.

The naming convention is [thing, setThing]. Functions whose names start with use are called hooks: they let a component "hook into" features React manages, like state.

Here is what happens on a click:

One click, step by step
  1. Eventthe click handler calls setCount(1)
  2. ScheduleReact stores 1 and queues a re-render
  3. RenderReact calls App() again; useState(0) now returns 1
  4. CommitReact updates the button text in the DOM

The handler calls setCount(count + 1), which is setCount(1). Nothing on screen has changed yet.

1/4

The initial value is only used on the first render. After that, useState returns whatever was last stored.

The rules of hooks

React does not know your state's variable names. It tracks state by the order hooks are called inside a component: first useState call, second useState call, and so on. So two rules keep that order identical on every render:

  • Call hooks only at the top level of a component (or of a custom hook). Never inside if, loops or nested functions.
  • Call hooks only from React function components or custom hooks, not from regular functions.
function Profile({ isAdmin }: { isAdmin: boolean }) {
  // Wrong: on some renders this hook is skipped, shifting every hook after it
  if (isAdmin) {
    const [panelOpen, setPanelOpen] = useState(false);
  }
 
  // Right: always call it, then use the value conditionally
  const [panelOpen, setPanelOpen] = useState(false);
  // ...
}

The ESLint plugin eslint-plugin-react-hooks (included in Vite and Next.js templates) flags these mistakes for you.

Multiple pieces of state

A component can call useState as many times as it needs. Keep separate values that change independently in separate state variables.

React
import { useState } from "react"; export default function App() { const [name, setName] = useState(""); const [likes, setLikes] = useState(0); const [showDetails, setShowDetails] = useState(false); return ( <div> <input aria-label="Name" placeholder="Your name" value={name} onChange={(e) => setName(e.target.value)} /> <p>Hello, {name || "stranger"}!</p> <button onClick={() => setLikes(likes + 1)}>Like ({likes})</button>{" "} <button onClick={() => setShowDetails(!showDetails)}>{showDetails ? "Hide" : "Show"} details</button> {showDetails && <p>Details: you have liked this {likes} times.</p>} </div> );}

Do not store anything you can compute from other state or props. If you have firstName and lastName, write const fullName = firstName + " " + lastName during render. A separate fullName state would have to be kept in sync by hand, and one day it will not be.

Predict the outputJavaScript

The user clicks the button twice. What does the button say?

function Toggle() {
const [on, setOn] = useState(false);
return (
  <button onClick={() => setOn(!on)}>
    {on ? "ON" : "OFF"}
  </button>
);
}
Need a nudge? Hints walk you through it.

State belongs to each instance

State is not attached to the function. It is attached to each place the component appears in the tree. Render <Counter /> twice and you get two independent counters.

React
import { useState } from "react"; function Counter({ label }: { label: string }) { const [count, setCount] = useState(0); return ( <p> {label}: <button onClick={() => setCount(count + 1)}>{count}</button> </p> );} export default function App() { return ( <div> <Counter label="Apples" /> <Counter label="Pears" /> </div> );}
Two counters, two separate states
AppCounter (Apples)state: countCounter (Pears)state: countroot

Each Counter in the tree gets its own count. React keeps them in separate slots.

1/3

State is also private. The parent App cannot read either count. If the parent needs it (say, to show a total), the state has to move up into the parent, which is the lifting state up lesson.

Quick check
You render <Counter /> in three places and click the second one 5 times. What do the three show?
Need a nudge? A hint rules out a wrong answer.

Initial state from a function

Sometimes computing the initial value is expensive, like reading and parsing saved data. Writing useState(loadDrafts()) calls loadDrafts() on every render, even though React only uses the result on the first one. Pass the function itself instead and React calls it once:

// Runs loadDrafts() on every render, then throws the result away
const [drafts, setDrafts] = useState(loadDrafts());
 
// Runs loadDrafts() only on the first render
const [drafts, setDrafts] = useState(loadDrafts);
const [prefs, setPrefs] = useState(() => JSON.parse(localStorage.getItem("prefs") ?? "{}"));

This is called an initializer function (or lazy initial state). Cheap values like 0, "" or [] do not need it.

Match the pairs0/4 matched

Match the code to what it does.

Choose an item, then its match on the other side.
ChallengeEasy

Counter with limits

Build a counter.

  • A <p> showing Count: 0 to start.
  • Three buttons: Increment (adds 1), Decrement (subtracts 1) and Reset (back to 0).
  • The count must never go below 0: the Decrement button is disabled while the count is 0.
Count: 2   [Increment] [Decrement] [Reset]
React
import { useState } from "react"; export default function App() { let count = 0; // this will not work: use state instead return ( <div> <p>Count: {count}</p> <button>Increment</button> <button>Decrement</button> <button>Reset</button> </div> );}
ChallengeEasy

Bio with a character limit

Build a bio field with a 20-character limit.

  • A <textarea aria-label="Bio"> controlled by state.
  • Below it, a <p> with the class counter showing length/20, for example 5/20.
  • When the text is longer than 20, the counter also gets the class over (so its className is counter over).
  • A Save button that is disabled when the bio is empty or over the limit.
[hello              ]
5/20        [Save]
React
import { useState } from "react"; const LIMIT = 20; export default function App() { return ( <div> <textarea aria-label="Bio" /> <p className="counter">0/{LIMIT}</p> <button>Save</button> </div> );}
Key terms
state
Data a component remembers between renders. Changing it with the setter triggers a re-render.
useState
The hook that returns [value, setValue]. The argument is the initial value, used only on the first render.
re-render
React calling your component function again to get fresh JSX, usually because state changed.
rules of hooks
Call hooks only at the top level of components or custom hooks, never in conditions or loops, so their order is stable.
initializer function
Passing a function to useState(fn) so an expensive initial value is computed only once.