A click handler calls setCount(count + 1) three times. What is count after one click?
EasyP1Output
A React component's click handler calls setCount(count + 1) three times in a row, starting from count = 0. What is count after one click? The snippet models React's update queue; it prints the result for that handler and then for the same handler written with setCount(c => c + 1).
1// A simplified model of React's update queue.2function click(count, makeUpdates) {3 const queue = [];4 const setCount = (update) => queue.push(update);5 makeUpdates(count, setCount);6 return queue.reduce((s, u) => (typeof u === 'function' ? u(s) : u), count);7}8console.log(click(0, (count, set) => { set(count + 1); set(count + 1); set(count + 1); }));9console.log(click(0, (count, set) => { set((c) => c + 1); set((c) => c + 1); set((c) => c + 1); }));
Saved automatically
One line per console.log. Arrays as [1, 2, 3], objects as { a: 1 }, an uncaught error as Uncaught TypeError: message (Chrome and Node wording).
Hints
Saved automatically