CPCODELAB
React

State with useState

11 min read

Remembering Values Between Renders

Regular JavaScript variables reset on every render. useState gives a component persistent memory — when you call the setter, React re-renders the component with the new value.

jsx
import { useState } from 'react';

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

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
      <button onClick={() => setCount(c => c - 1)}>Decrement</button>
      <button onClick={() => setCount(0)}>Reset</button>
    </div>
  );
}

Functional updates

When the new state depends on the old state, always use the functional form of the setter: setState(prev => prev + 1). This guarantees you get the most recent value, even when multiple state updates are batched.

State updates are asynchronous and batched. After calling setCount(5), the variable count still holds the old value on the same line. The new value is available only on the next render.

Ready to test yourself?
Practice React— quiz & coding exercises