State with useState — React

State is data a component remembers between renders. const [count, setCount] = useState(0) keeps state with a starting value of 0. count is the value in this…

A like button whose number goes up on every click sounds easy: make a variable, add 1 on each click. Try it, and the number stays at 0. A component needs a way to remember data between renders, and React gives it one through state.

State is data a component remembers between renders, such as the number on a counter or whether a button is switched on. You keep it with the useState hook (a hook is a special React function whose name starts with use). useState also gives you a setter: a function that replaces the state's value. Once state is replaced through its setter, React runs that component again (a re-render) and then updates the page to match the result.

Picture the scoreboard at a futsal match. The operator holds the score, not the players. A player can only say "make it 1". The operator then shows the new number, and everyone reads the new board. In React, the operator is React, the score is the state, and the player is your code that calls the setter. The number on the board right now is the state's value in the render that's running.

Why a plain variable isn't enough

This counter keeps its number in a plain variable, count:

function Counter() {
  let count = 0

  return (
    <button onClick={() => { count = count + 1 }}>
      Clicked {count} times
    </button>
  )
}

However many times you click, the button still says "Clicked 0 times". There are two reasons:

State solves both: React keeps the value outside the function, and the setter asks for a re-render.

useState: the value and the setter

This is the same counter, but its number is kept in state:

import { useState } from "react"

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

  return (
    <div>
      <span id="count">{count}</span>
      <button id="increment" onClick={() => setCount(count + 1)}>+1</button>
    </div>
  )
}

This table shows the value of count from click to click:

Event count in this render What's asked for Shown
First render 0 0
Click +1 0 setCount(0 + 1)
2nd render 1 1
Click +1 1 setCount(1 + 1)
3rd render 2 2

A switch: true or false state

State doesn't have to be a number. For a switch (something that goes back and forth between on and off), keep a boolean and flip it:

function App() {
  const [active, setActive] = useState(true)

  return (
    <div>
      <p id="status">{active ? "Active" : "Inactive"}</p>
      <button id="toggle" onClick={() => setActive(!active)}>Toggle</button>
    </div>
  )
}

Each render holds its own value

Take a guess first. count starts at 0, and one click runs setCount(count + 1) three times in a row. Does the number become 1 or 3?

Inside one render, count is a constant: its value doesn't change until that render is over. setCount doesn't change the count the handler is holding. setCount schedules a new render with the new value. Here is a click handler with those three calls:

function handleClick() {
  setCount(count + 1) // count in this render is 0: asks for "make it 1"
  setCount(count + 1) // count is still 0: "make it 1" again
  setCount(count + 1) // same: "make it 1"
  console.log(count)  // 0, this render's value
}

One click from 0 gives 1, not 3. It's like telling the operator "make it 1" three times: the board still says 1. console.log(count) prints 0, because this handler belongs to the render where count is 0. The value 1 only exists in the next render.

If you want "add 1" three times, send a function to the setter, not a value:

function handleClick() {
  setCount(c => c + 1) // queue: 0 + 1 = 1
  setCount(c => c + 1) // queue: 1 + 1 = 2
  setCount(c => c + 1) // queue: 2 + 1 = 3
}

Objects and arrays: make a new one

React compares the old state with the new one. If you send the setter the exact same object (not a copy of it), React treats it as unchanged, and the screen isn't updated. In this example, user is a state that holds an object, and items is another state that holds an array:

const [user, setUser] = useState({ name: "Budi", age: 17 })

user.age = 18                  // wrong: changes the old object
setUser(user)                  // the same object, the screen doesn't change

setUser({ ...user, age: 18 })  // right: a new object, its contents copied and age replaced
setItems([...items, "new"])    // a new array with one extra item

⚠️ When the number won't change, or React throws an error

TL;DR: State is data a component remembers between renders. const [count, setCount] = useState(0) keeps state with a starting value of 0. count is the value in this render, and it doesn't change during that render. setCount(...) (the setter) schedules a new render with the new value, so a console.log(count) after it still prints the old value. setCount(count + 1) three times in one click adds only 1, while setCount(c => c + 1) three times adds 3. For a switch (on/off), keep a boolean and flip it with setActive(!active). Objects and arrays are replaced with new ones ({ ...user, age: 18 }), never changed in place. Hooks (React functions whose names start with use), useState included, are always called at the outermost level of the component, not inside an if or a loop.

⚡ A plain variable isn't enough

Guess first: a button that says Clicked {count} times uses let count = 0 and count = count + 1 in its onClick. After 5 clicks, what does it say?

Still "Clicked 0 times". Changing a plain variable tells React nothing, so React doesn't run the component again. Even if it did, let count = 0 would set the value back to zero.

Meaning: State is data a component remembers between renders. You keep it with the useState hook (a hook is a special React function whose name starts with use).

⚡ useState: a value and a setter

Write:

import { useState } from "react"

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

  return (
    <div>
      <span id="count">{count}</span>
      <button id="increment" onClick={() => setCount(count + 1)}>+1</button>
    </div>
  )
}

Meaning: count is the value in this render, and setCount is the setter, the function that replaces it. Once state is replaced through its setter, React runs the component again (a re-render). The 0 is only used on the first render.

⚡ Up by 1 or by 3?

Write:

setCount(c => c + 1)
setCount(c => c + 1)
setCount(c => c + 1)
Guess first: count starts at 0. If the code above calls setCount(count + 1) three times instead, how much does one click raise count?

Only 1. All three read the same count from this render, which is 0, so they all ask for "make it 1". With c => c + 1, as in the code above, it goes up by 3.

Meaning: c => c + 1 is called an updater function. React runs the three updaters in order, and each one receives the latest value (the result of the updater before it), not this render's value.

⚡ Objects and arrays: make new ones

Write:

setUser({ ...user, age: 18 })

Meaning: user is a state that holds the object { name: "Budi", age: 17 }. React compares the old state with the new one, so an old object that was changed and sent again counts as the same, and the screen doesn't change. Copy its contents into a new object with ...user, then replace the part that changes.

What you will learn