🎓 A1Learner
🔍
0 of 50 lessons completed

Updating State

Updating state means calling the setter function with a new value. React then renders the component again with the new value.

Call the setter

setCount(1) asks React to show 1 next.

function handleClick() {
  setCount(1);
}

Wire it to a button

A click runs handleClick.

<button onClick={handleClick}>Set to 1</button>

Build on the old value

count + 1 builds the next value from the current one.

function addOne() {
  setCount(count + 1);
}

Example

import { useState } from 'react';

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

  function handleClick() {
    setCount(1);
  }

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={handleClick}>Set to 1</button>
    </div>
  );
}

Key points

  • Call the setter with the new value.
  • React renders the component again after the setter runs.
  • The new value appears in the next render.
  • The old value stays on screen until the re-render.
  • Build the next value from the current one when it depends on it.

In this example, App starts count at 0. handleClick calls setCount with 1. App returns a paragraph and a button. The paragraph shows Count: 0 at first. A click runs handleClick. React renders again, and the paragraph shows Count: 1.

Note

Never assign a new value to the state variable directly.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

How do you change a state value?