Easy javascript

useState counter logic

Problem

Simulate useState: start at 0, increment twice, print final value.

Hints
  • setState(s => s + 1) twice

Your practice code

Ready — edit the code above and click Run.

Solution

let state = 0;
function setState(updater) {
  state = typeof updater === "function" ? updater(state) : updater;
}
setState(s => s + 1);
setState(s => s + 1);
console.log(state);

Try solving on your own first, then reveal the official answer.

Explanation

Functional updates avoid stale state—critical in async React interview answers.

Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details