Manage state with useState
Keep a changing value in a React 19 component with useState, and see why the setter schedules a re-render instead of changing the variable.
A counter that never updates is the first thing everyone writes in React. A plain variable resets on every render, so the value has to live in state.
import { useState } from 'react';
export function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}Clicked 0 times (first render)
Clicked 1 times (after one click)
Clicked 2 times (after two clicks)useState(0) returns the current value and a setter. Calling setCount does not change count in the code that is already running, it asks React to render the component again with the new value. That is why logging count straight after setCount(count + 1) still prints the old number, as the useState reference explains.
State is kept per component instance, so two Counter elements count separately. Do not put values you can compute from props or other state into state, because you then have two sources of truth to keep in sync.