React Foundations ยท State

Updating state with a function

Functional state updates

Updating state with a function

Here is a trap that catches almost everyone. You write a handler that updates the count twice, click it once, and the count goes up by one instead of two.

Each line reads count from the same render. Both lines see the same starting value, so both compute the same next number, and the second overwrites the first.

When the next state depends on the previous state, pass a function to the setter instead of a value:

setCount((current) => current + 1);

React calls that function with the latest state and uses the return value as the next state. The parameter is always up to date, even when several updates queue inside one event.

function addTwo() {
  setCount((current) => current + 1);
  setCount((current) => current + 1);
}

Now the second update receives what the first produced, so the two together add two. Use the functional form whenever the new value is derived from the old one.

Your job is to add two to the count in a single click. The component is exported from App.jsx.

Challenge

A press needs to add two to the count, not one. Export an App component from App.jsx that renders a button labelled Count: 0 and adds two to the count each time it is clicked, using the functional updater form of the setter.

The Test clicks the button once and expects the label to read Count: 2. The starter never changes the count, so the Test fails.

App.jsx
export function App() {
  return <button>Count: 0</button>;
}

No test run yet

The Test is hidden. Run it to check the Challenge โ€” you only see the result, never the test source.