Home / Learn React / State with useState

State with useState

State is a component's memory. When state changes, React runs the component again and the screen updates. The hook for it is useState.

In shortconst [value, setValue] = useState(initial). Call setValue to change it. React then re-renders.

Theory in plain words

The state loopState (count = 0)Render UIfrom stateUser event(click)setCount(1)new state starts a new render
The state loop

What it is

State is data that belongs to one component and can change over time: a counter, the text in an input, whether a menu is open. useState returns the current value and a function to change it.

Why we use it

A normal variable is reset every time the component function runs, and changing it does not update the screen. State is kept by React between renders and changing it tells React to render again.

How it works

React stores the state outside your function, in a slot for that component. On every render it hands you the current value. Calling setX(new) schedules a render. During that render useState returns the new value.

Where it is used

  • Counters, likes, toggles, tabs
  • Form fields and filters
  • Open or closed menus, modals and accordions
  • Data you loaded from a server

A counter

useStateTry it Yourself

In a real project write import { useState } from "react" and use useState(0).

Why not a normal variable?

Variable vs stateTry it Yourself

The variable changes (see the console) but the screen does not, and it resets on the next render.

Many states, each independent

Several useState callsTry it Yourself

Each component copy has its own state

Two countersTry it Yourself

Clicking A does not change B. State belongs to one place in the tree.

Careful:Never change state directly: count = count + 1 does nothing. Always call the setter. Also do not call hooks inside loops, conditions or nested functions.

Quick quiz

1. What does useState return?

2. Why does changing a normal variable not update the screen?

3. Do two copies of a component share state?

Common questions

What does useState return?

An array: the current value and a setter. const [value, setValue] = useState(initial).

Why does changing a normal variable not update the screen?

React is not told to render again, and the variable resets. Only state changes trigger a render and state survives renders.

Do two copies of a component share state?

No, each copy has its own state. State belongs to a component instance position in the tree.