Thuta Learning
React
BasicWeb DevelopmentIntermediate

State (useState)

ReactLesson 730 min

What you'll walk away with

  • Explain why changing a plain variable does not update the screen
  • Write const [value, setValue] = useState(initial) and know what the value and the setter each do
  • Predict the difference between setCount(count + 1) and setCount(c => c + 1)
  • Update array and object state with fresh copies instead of mutation
  • Follow the rule that hooks are called only at the top level of a component

Explain it simply

Explain it simply

State is a component's memory. How many times a button has been clicked, what is typed in an input, whether a modal is open, what is in the cart: data that changes over time and must show on screen is state.

Props are data the parent gives you; state is data the component owns and can change. When you call the setter function React provides, React calls the component again and updates the screen with the new value.

Problem → Why → Solution

The problem: the variable changes but the screen does not

Almost everyone's first counter looks like this: declare let count = 0, and on click run count = count + 1. The console shows 1, 2, 3 counting up, yet the page keeps saying "Clicked 0 times" forever.

BrokenCounter.jsx
function BrokenCounter() {
  let count = 0;

  function handleClick() {
    count = count + 1;
    console.log(count); // 1, 2, 3... in the console
  }

  return <button onClick={handleClick}>Clicked {count} times</button>; // always 0
}

Why doesn't the screen change?

There are two reasons. First, React does not notice a local variable changing, so it never re-renders the component. Second, even if something else caused a render, the function would run from the top, let count = 0 would execute again, and the increments would be lost. useState fixes both: React keeps the value between renders, and calling the setter requests a new render.

Core concept: useState and the render snapshot

const [count, setCount] = useState(0); uses array destructuring to take two items. count is the current value for this render, and setCount is a function that stores a new value and requests a re-render. The 0 in useState(0) is the initial value, used only on the first render; on later renders React hands back the value it stored. Naming the pair [something, setSomething] is the convention.

Calling setCount does not change the count variable right away. Within one render, state is fixed like a snapshot, and that render's event handlers only see the snapshot's value. So console.log(count) straight after setCount(count + 1) prints the old value. Calling setCount(count + 1) three times in one handler is also "0 + 1" three times, so the result is 1. React queues the updates until the handler finishes (batching) and then renders once.

When the new value depends on the old one, pass an updater function: setCount(c => c + 1). React runs queued updaters in order, feeding each the latest value, so three calls give 3.

Never modify array or object state in place. React compares old and new values with Object.is, so items.push(x) followed by setItems(items) hands back the same array, and React can skip the re-render because nothing appears to have changed. Create a fresh copy instead: setItems([...items, x]) or setUser({ ...user, name: "Mya" }).

State belongs to each component instance: two <Counter /> elements have two separate counts. Hooks must be called at the top level of a component, never inside if statements, loops or nested functions, because React tracks hooks by the order they are called.

Mental model: set, re-render, new snapshot
  1. A render uses one state snapshot
  2. A handler calls the setter
  3. React calls the component again
  4. The UI shows the new snapshot

You never change state in place; you request a new value for the next render.

General pattern

jsx
import { useState } from "react";

function ComponentName() {
  const [value, setValue] = useState(initialValue);

  setValue(newValue);                          // replace
  setValue((previous) => nextFrom(previous));  // compute from the latest
  setList([...list, newItem]);                 // arrays: new copy
  setObject({ ...object, key: newValue });     // objects: new copy
}

Call useState at the top of the component to get [value, setter]. Setters belong inside event handlers, not directly in the render body; the lines here only show the shapes of the calls.

Example: a click counter

This Counter is the BrokenCounter from the problem section, fixed with useState. Each click runs increase, which calls setCount with an updater function; React re-renders the component and the new number appears.

jsx
import { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  function increase() {
    setCount(previousCount => previousCount + 1);
  }

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={increase}>Click me</button>
    </div>
  );
}

Code breakdown

  1. Line 1import { useState } from 'react';

    useState is a hook imported by name from the react package. Functions whose names start with use are called hooks.

  2. Line 4const [count, setCount] = useState(0);

    On the first render count is 0. On later renders React returns the stored value, so the 0 is not used again. Note that the hook is called at the component's top level.

  3. Lines 6-8setCount(previousCount => previousCount + 1);

    The updater receives the latest value from React as previousCount and adds one. Since it runs once per click, setCount(count + 1) would also work here, but the updater is the safer habit.

  4. Line 12<p>You clicked {count} times</p>

    Each render shows its own count snapshot. It starts as "You clicked 0 times", and every click produces a new render with the next number.

  5. Line 13<button onClick={increase}>Click me</button>

    increase is passed as a reference, not called. Writing onClick={increase()} would call it during render, setting state while rendering and causing an endless re-render error.

You should see
Every time you click the button, the number in the UI increases — `You clicked 1 times`, `2 times`, and so on.

Seeing the snapshot for yourself

Put this component in App.jsx and try both buttons. One click on "+3?" adds only 1, and the console prints the old value 0. The "+3" button uses updaters, so it really adds 3.

Snapshot.jsx
import { useState } from "react";

export default function Snapshot() {
  const [count, setCount] = useState(0);

  function addThreeWrong() {
    setCount(count + 1); // 0 + 1
    setCount(count + 1); // still 0 + 1
    setCount(count + 1); // still 0 + 1
    console.log(count);  // 0: this render's snapshot
  }

  function addThree() {
    setCount((c) => c + 1);
    setCount((c) => c + 1);
    setCount((c) => c + 1);
  }

  return (
    <div>
      <p>{count}</p>
      <button onClick={addThreeWrong}>+3?</button>
      <button onClick={addThree}>+3</button>
    </div>
  );
}

In real projects

In real projects

useState appears almost everywhere in real apps: whether a dropdown is open (isOpen), which tab is selected (activeTab), form input values, shopping cart items, whether something is loading (isLoading). The hard decision is where state should live: if two components need the same value, keep it in their closest common parent and pass it down as props.

Experienced developers keep state minimal. If cart items are already in state, the total price is calculated from them on every render rather than stored separately, because duplicated state invites bugs where one copy is updated and the other forgotten. When update logic grows complex, teams switch to useReducer (in the Intermediate chapter), and for state shared by many components they use context or a state library.

Common mistakes

Common mistakes

1. Reading the new value right after setting it

In setCount(count + 1); if (count === 10) {...}, the if still checks the old value. If you need the new value immediately, compute it first, const next = count + 1;, then use next for both setCount(next) and if (next === 10).

2. Mutating array or object state

items.push(newItem); setItems(items); passes back the very same array, so React may see no change and the screen does not update. Create a new array: setItems([...items, newItem]). Use filter to remove and map to edit, since both return new arrays.

3. Calling a hook inside a condition

Writing if (isLoggedIn) { const [name, setName] = useState(""); } changes the number of hooks between renders, so React mismatches state and may throw an error such as "Rendered more hooks than during the previous render". Always call useState at the top and apply the condition in the JSX.

4. Calling the setter directly in onClick

<button onClick={setCount(count + 1)}> calls setCount during render, which requests another render, which calls it again, ending in a "Too many re-renders" error. Wrap it in an arrow function: onClick={() => setCount(count + 1)}.

Best practices

Best practices

  • Do not store values you can compute from other state or props, such as a total or a filtered list; calculate them during render.
  • Make the updater function your habit whenever the next value depends on the previous one.
  • Name state clearly as a value and setter pair, such as isOpen and setIsOpen or items and setItems.
  • Group values that always change together, such as x and y, into one object instead of two separate states.

Mini challenge

Mini challenge: a step counter

Write a StepCounter with two pieces of state, count and step. Count goes up and down by step and must never drop below 0.

  • Keep count (starting at 0) and step (starting at 1) in two useState calls
  • The +step and -step buttons change count with updater functions
  • -step uses Math.max(0, ...) so count never goes below 0, and the button is disabled at 0
  • One button switches step between 1 and 5, and a Reset button sets count back to 0
StepCounter.jsx
import { useState } from "react";

export default function StepCounter() {
  // TODO: count state (0) and step state (1)

  function increase() {
    // TODO: add step using an updater function
  }

  function decrease() {
    // TODO: subtract step, but never below 0
  }

  return (
    <div className="step-counter">
      {/* TODO: "Count: N" */}
      {/* TODO: +step button, -step button (disabled at 0) */}
      {/* TODO: button that switches step 1 <-> 5, and a Reset button */}
    </div>
  );
}

Expected: It starts at "Count: 0" with the -1 button disabled. Clicking +1 twice shows Count: 2; switching to step 5 and clicking +5 shows Count: 7; clicking -5 twice stops at 0 instead of -3, and the minus button is disabled again.

Show hint

An updater can use step: setCount((current) => current + step). For the step button, a ternary works: setStep(step === 1 ? 5 : 1).

Show solution
StepCounter.jsx
import { useState } from "react";

export default function StepCounter() {
  const [count, setCount] = useState(0);
  const [step, setStep] = useState(1);

  function increase() {
    setCount((current) => current + step);
  }

  function decrease() {
    setCount((current) => Math.max(0, current - step));
  }

  const otherStep = step === 1 ? 5 : 1;

  return (
    <div className="step-counter">
      <p>Count: {count}</p>
      <button onClick={increase}>+{step}</button>
      <button onClick={decrease} disabled={count === 0}>
        -{step}
      </button>
      <button onClick={() => setStep(otherStep)}>Use step {otherStep}</button>
      <button onClick={() => setCount(0)}>Reset</button>
    </div>
  );
}

Quick quiz 1 / 3

count is 0 and one handler calls setCount(count + 1) three times. What is count on the next render?

Quick quiz 2 / 3

With const [items, setItems] = useState([]);, which correctly adds a new item?

Quick quiz 3 / 3

What is wrong here: function Profile({ show }) { if (show) { const [name] = useState("Mya"); } ... }

What to remember

  • React does not notice plain variables and resets them every render, so use useState for data that changes.
  • const [value, setValue] = useState(initial): calling the setter re-renders the component with the new value.
  • State is a snapshot per render; when the next value depends on the previous one, use an updater like setCount(c => c + 1).
  • Update arrays and objects with fresh copies via spread, and call hooks only at the top level.

React Documentation — React

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

State (useState) | Thuta Learning