State with useState

Topic 2 of 4 in Interactivity & state7 min readIntermediateFree course

Overview

Components often need to remember things: the current image in a gallery, whether a menu is open, what’s in a shopping cart. This component-specific memory is called state, and you add it with the useState hook.

Why a regular variable doesn’t work

JSX
function Counter() {
  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
}

The console shows the variable increasing, but the screen never changes. Two problems:

  1. Changing a local variable doesn’t trigger a render. React has no idea anything changed.
  2. Local variables don’t survive renders. Even if the component did re-render, let count = 0 would run again and reset it.

useState solves both: it keeps a value between renders, and its setter triggers a new render.

Using useState

JSX
import { useState } from 'react';

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

  return (
    <button onClick={() => setCount(count + 1)}>
      Clicked {count} times
    </button>
  );
}

useState(0) returns an array of two things, which you destructure:

  • count — the current state value (0 on the first render),
  • setCount — a function that updates it.

Name them [something, setSomething] by convention.

A click calls handleClick, which calls setCount(1) to queue an update. React re-renders Counter, and the commit shows 1 in the DOM. useState stores the value between renders and gives you the latest one.

Here’s what happens when you click:

  1. React renders Counter. useState(0) returns [0, setCount].
  2. You click. The handler calls setCount(0 + 1).
  3. React stores 1 and schedules a re-render.
  4. React calls Counter again. This time useState(0) returns [1, setCount] — the initial value is ignored after the first render.
  5. React updates the DOM to “Clicked 1 times”.

Any kind of value

State can hold strings, numbers, booleans, arrays, objects — anything:

JSX
const [isOpen, setIsOpen] = useState(false);
const [query, setQuery] = useState('');
const [selectedId, setSelectedId] = useState(null);
const [tags, setTags] = useState(['react', 'hooks']);
const [form, setForm] = useState({ name: '', email: '' });

A component can have as many state variables as it needs. Prefer several simple variables over one big object when the values change independently.

Toggling a boolean

JSX
function FaqItem({ question, answer }) {
  const [isOpen, setIsOpen] = useState(false);

  return (
    <div>
      <button aria-expanded={isOpen} onClick={() => setIsOpen(!isOpen)}>
        {question}
      </button>
      {isOpen && <p>{answer}</p>}
    </div>
  );
}

State is private to each instance

Render the same component twice and each copy gets its own state:

JSX
<FaqItem question="Is there a certificate?" answer="Yes." />
<FaqItem question="Can I get a refund?" answer="Within 30 days." />

Opening one doesn’t open the other. State is tied to the component’s position in the tree, not to the function — React keeps a separate box of state for each place a component is rendered. (If two components need to share state, you’ll lift it up to a common parent — see Lifting state up.)

Lazy initial state

If the initial value is expensive to compute, pass a function — React calls it only on the first render:

JSX
// ✗ Reads localStorage on every render (the result is ignored after the first)
const [draft, setDraft] = useState(localStorage.getItem('draft') ?? '');

// ✓ Only reads it once
const [draft, setDraft] = useState(() => localStorage.getItem('draft') ?? '');

The Rules of Hooks

Functions starting with use — useState, useEffect, useContext and your own custom hooks — are hooks. React relies on hooks being called in the same order on every render, so there are two rules:

  1. Only call hooks at the top level of a component or custom hook — not inside if statements, loops, nested functions or after an early return.
  2. Only call hooks from React functions — components and custom hooks, not regular JavaScript functions or classes.
JSX
function Profile({ user }) {
  if (!user) return null;                       // early return…
  const [tab, setTab] = useState('courses');    // ✗ …then a hook: the order changes between renders
}

function Profile({ user }) {
  const [tab, setTab] = useState('courses');    // ✓ hooks first
  if (!user) return null;
  // …
}

The rules-of-hooks lint rule catches these mistakes as you type. It’s switched on in the Vite template’s Oxlint config, and it’s in eslint-plugin-react-hooks if your project uses ESLint.

One exception: the use API (for reading promises and context, covered in Suspense and use) can be called inside conditions. It’s the only one.

Seeing state in DevTools

Open React DevTools → Components, select a component, and you’ll see its hooks with their current values. You can even edit state there to test how the UI reacts.

Rule of thumb: if a value changes over time because of user interaction and the screen should reflect it, it’s state. If it never changes, it’s a constant. If you can calculate it from other values, it’s neither — compute it during render.

Exercise

A like button and an image gallery

Write LikeButton that shows “♡ 12” and toggles between liked (“♥ 13”) and not liked (“♡ 12”) on each click, using one boolean state. Then write Gallery({ images }) that shows one image at a time with “Previous” and “Next” buttons, “Image N of M”, and disables Previous on the first image and Next on the last.

JavaScript
import { useState } from 'react';

export function LikeButton() {
  // your code here
}

export function Gallery({ images }) {
  // your code here
}

Summary

  • Regular variables reset on every render and changing them doesn’t re-render — that’s why you need state.
  • const [value, setValue] = useState(initial) gives you the current value and a setter.
  • Calling the setter stores the new value and asks React to re-render the component.
  • Each component instance has its own, private state.
  • Hooks must be called at the top level of a component or custom hook — never in conditions, loops or nested functions.