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:
- Changing a plain variable tells React nothing, so there's no re-render.
- Even if there were a re-render, the
Counterfunction runs again from the top, andlet count = 0sets it back to zero.
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>
)
}
import { useState } from "react"takes the hook from React. The starter in the exercise editor begins with this line too, just as in a real project.useState(0):0is the starting value, and it's only used on the first render.useStatereturns an array holding two things, andconst [count, setCount]names them (this is array destructuring).countis the current value.setCountis its setter. The names are up to you, but the habit is[something, setSomething].setCount(count + 1)asks React: "the next count is 1 bigger". React runsCounteragain, and this timeuseStatereturns the new value.
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>
)
}
useState(true)makes it start switched on, so the paragraph starts asActive.active ? "Active" : "Inactive"picks one of the two words based on the state.setActive(!active)stores the opposite. One click makes itInactive, another click brings backActive.
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
}
c => c + 1is called an updater function. React keeps all three in a queue (a waiting line), then runs them in order. Each updater receives the result of the one before it asc.- The result is 3, with just one render. React first collects every request from one event (this is called batching), then renders once.
- A practical rule: is the new value calculated from the old one (add, subtract, flip true/false)? Use an updater:
setCount(c => c + 1),setActive(a => !a). Is the new value unrelated to the old one, as insetCount(0)? Send the value directly.
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
count++orcount = 5.countis aconst, and changing it doesn't trigger a render. Always go through the setter, such assetCount(...)orsetActive(...).- Forgetting the starting value.
useState()with no number makescountundefined, and{undefined}shows nothing. A counter that must start at 0 is writtenuseState(0). - useState inside an
ifor a loop. A hook must be called at the outermost level of the component, not inside anif, a loop or another function. That way the order of the calls is the same on every render, and React recognises each piece of state by that order. - Calling the setter directly in the component body.
setCount(0)outside a handler triggers a render, and that render callssetCountagain, over and over. React stops with a "Too many re-renders" 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.