Skip to the solution
MediumFrontend5 min read

Implement a Minimal useState Hook Using Closures (How React's State Actually Persists Between Renders)

841 views

The problem

Problem, as an interviewer would state it: "Implement a minimal version of React's useState hook, WITHOUT React itself — explain, with a real working example, how state actually persists across re-renders when a component is 'just a function' that gets called again."

Examples:

Code
const [count, setCount] = useState(0);
setCount(5);
// on the NEXT render, useState(0) returns 5, not 0 -- state persisted OUTSIDE the function call

Clarifying questions expected:

  • Does this need to support MULTIPLE useState calls in one component, each with its own independent slot?
  • Should setState support a functional-update form, like React's real setCount(prev => prev + 1)?
  • Is this scoped to one component instance, or shared globally (a real, important distinction)?

Code / implementation expected: Yes — real, direct proof that state persists across simulated re-renders, that multiple useState calls stay independent, and that a functional update correctly reads the previous value.

  • react
  • closures
  • hooks

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

5 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: a minimal useState reimplementation correctly persists state across simulated renders, with independent slots and functional updates

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 101 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

Object Difference

Continue