State Updates and Snapshots
State is a snapshot for each render. Setting state does not change the variable in the current render. Use the updater form when the next value depends on the previous one.
Example
let state = 0;
const setState = (fn) => { state = typeof fn === "function" ? fn(state) : fn; };
setState((s) => s + 1);
setState((s) => s + 1);
console.log(state);
let snap = 0;
const inc = () => { setS(snap + 1); setS(snap + 1); };
function setS(v) { snap = v; }
inc();
console.log(snap);Result
2 2
Exercise
Updater form.
setN(n => n 1)
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.