A regular JavaScript variable inside a component resets to its initial value every single time the component re-renders โ it can't "remember" anything across renders, and changing it doesn't trigger a re-render in the first place. State solves both problems: React remembers it between renders, and updating it automatically triggers a fresh render with the new value.
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>
Increase
</button>
</div>
);
}useState(0): creates a state variable starting at0const [count, setCount]: array destructuring โcountis the current value,setCountis the function used to update itsetCount(count + 1): updates state and triggers React to re-render the component with the new value
const [count, setCount] = useState(0);
const [name, setName] = useState("");
const [isVisible, setIsVisible] = useState(true);
// Functional update - safer when the new value depends on the previous one
setCount((previousCount) => previousCount + 1);A component can have as many independent useState calls as needed. The functional update form โ passing a function instead of a raw value โ guarantees you're working from the most current state, which matters especially when updates happen in quick succession.
State updates are not immediate โ calling setCount(count + 1) and then logging count on the very next line still shows the old value, because the update only takes effect on the component's next render. If you need the new value right away for further logic, use the functional update form or a useEffect (Chapter 19).
Build a toggle button that switches a boolean isOn state between true and false, displaying "ON" or "OFF" accordingly.
import { useState } from "react";
function ToggleButton() {
const [isOn, setIsOn] = useState(false);
return (
<button onClick={() => setIsOn(!isOn)}>
{isOn ? "ON" : "OFF"}
</button>
);
}
Q Why does my component re-render when state changes?
That's the entire purpose of state โ React is designed to automatically call your component function again and update the DOM whenever a state setter (like setCount) is called, keeping the UI in sync with the data.
Q Can I use a regular variable instead of useState for something that changes?
Technically you can declare it, but changing it won't trigger a re-render, so the screen simply won't update to reflect the new value. Anything that should visibly update the UI must live in state.