Reactbeginner 8 min
Give a component memory with useState so the screen updates when data changes.
How useState stores a value that can change, and how updating it re-renders the component.
Counters, form inputs, toggles and menus all have data that changes over time. State is how React remembers it and updates the screen for you.
A normal variable inside a component is reset every time the component runs. State is a value React remembers between renders.
You create it with the useState hook:
count is the current value (starts at 0).setCount is the function that changes it.When you call setCount(newValue), React updates the value and re-runs the component, so the screen shows the new number.
Never change state directly (count = count + 1 does nothing useful). Always use the setter.
useState(0) starts count at 0. React remembers it across renders.setCount(count + 1), which stores 1 and re-renders.Count: 1. Each click adds one more.The runner on this page makes useState, useEffect and the other hooks available for you.
Add a "Subtract one" button, and stop the count from going below zero.
count = count + 1 does not re-render.useState gives a component memory.Next: events and handling user input.
const [count, setCount] = useState(0);function App() {
const [count, setCount] = useState(0);
return (
<div style={{ fontFamily: "system-ui" }}>
<h2>Count: {count}</h2>
<button onClick={() => setCount(count + 1)}>Add one</button>
<button onClick={() => setCount(0)}>Reset</button>
</div>
);
}