Props pass data down, but nothing so far can change while the app is running. Click a button, type in a box, check a box. The screen has to react. That's state.
A variable that changes doesn't update the screen. State does.
Regular variable (does nothing):
function Light() {
let isOn = false;
function toggle() {
isOn = !isOn;
}
return <button onClick={toggle}>{isOn ? "ON" : "OFF"}</button>;
}
Click this button and nothing happens on screen. isOn is flipping under the hood, but React never finds out, so it never re-renders.
useState is the fix. Same idea, but now React knows when the value changes:
import { useState } from "react";
function Light() {
const [isOn, setIsOn] = useState(false);
function toggle() {
setIsOn(!isOn);
}
return <button onClick={toggle}>{isOn ? "ON" : "OFF"}</button>;
}
useState(false) returns two things: the current value, and a function to update it. Calling the setter does two things: it saves the new value, and it triggers a re-render, React running the component again and updating the screen to match.
useState is called a hook. That's why it starts with use. More on that later.
Rules:
const [value, setValue] = useState(initialValue)isOn = true is wrong). Always use the setter (setIsOn(true))| Task | Code |
|---|---|
| Create state | const [isOn, setIsOn] = useState(false) |
| Read state | isOn |
| Update state | setIsOn(true) |
| Toggle state | setIsOn(!isOn) |