How does useState work?

React state and events · Freshers

Model answer

useState takes an initial value and returns an array with the current value and a setter function: const [count, setCount] = useState(0). Calling setCount(5) stores the new value and re-renders the component.

When the new value depends on the old one, pass a function: setCount((c) => c + 1). This is safe even when updates are batched.

Learn this topic

React useState Explained: Make Your Page React to Change in the course React.js Full Course: Beginner to Advanced.

Sign in to add your own answer.

More questions