Skip to content
jshacks.dev
Frameworks

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.

1 min read
Summarize in AI

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.

src/Counter.jsxJSX
import { useState } from 'react';

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

  return (
    <button onClick={() => setCount(count + 1)}>
      Clicked {count} times
    </button>
  );
}
Text
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.

Taggedreact 19
Share

More snippets

Frameworks

Update state from the previous value

Pass an updater function to the React state setter when the next value depends on the last one, so batched updates do not overwrite each other.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.