CodeBlanks Logo Icon CodeBlanks

Updating state

Learn to update state with the setter and use the previous value.

Updating state

To update state you call the updater function: setCount(count + 1). This computes the new value and tells React; React re-renders.

If the new value depends on the old one, the function form is safer: setCount(c => c + 1). It avoids confusion in back-to-back updates.

Never mutate state directly: count++ is wrong. React will not see it; always use the updater.

Re-render

When you call the updater, React schedules the new value and re-renders the component. The render may not be immediate; it can happen on the next tick, so back-to-back calls may batch.

This is why the function form setCount(c => c + 1) is recommended for updates based on the old value. Each call gets the latest value.

Re-rendering is cheap; React writes only the changed part to the DOM.

Practice Incrementing counter

Complete the skeleton. Write a Step component; import useState. Define const [n, setN] = useState(0);. Inside handleUp call setN(n => n + 1). Return <button onClick={handleUp}>{n}</button>. Export it.

Starter code

App.jsx
import { useState } from "react";

// Define Step here

Sample solution

App.jsx
import { useState } from "react";

function Step() {
  const [n, setN] = useState(0);
  function handleUp() { setN(n => n + 1); }
  return <button onClick={handleUp}>{n}</button>;
}

export default Step;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which increments count?

App.jsx
The updater function changes the state.
  • setCount(count + 1) Correct answer
  • count = count + 1
  • count++
  • setCount = count + 1

Explanation: setCount(count + 1) tells React the new value.

2 Updating state: fill in the missing part

Question
setCount(____)
Answer
setCount(count + 1)

Explanation: You added one to the current value.

3 Updating state: match the terms

Term Meaning
setCount(c => c+1) Function form
count++ Wrong mutation
setCount(0) Reset
re-render Re-render

All lessons in Beginner