ReactBeginner#hooks#state

What is useState and how do you update state correctly?

useState returns the current value and a setter. State updates are asynchronous and batched, so when the next value depends on the previous one use the updater function form.

Example
const [n, setN] = useState(0);
setN(n + 1); setN(n + 1);       // ends at 1
setN(p => p + 1); setN(p => p + 1); // ends at 2

Related Questions

1
ReactIntermediate#hooks#effects

Explain useEffect and its dependency array.

Open
2
ReactIntermediate#hooks

What are the rules of hooks?

Open
3
ReactIntermediate#hooks#refs

What is useRef used for?

Open