JS Guide
HomeQuestionsTopicsCompaniesResources
BookmarksSearch

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsreact
PrevNext

Learn the concept

Hooks

react
senior
hooks

Implement a basic version of useState from scratch.

hooks
useState
implementation
internals
closures
state
Quick Answer

A simplified useState uses a module-level array to store state values and an index counter to track which state slot to use. The setter updates the stored value and triggers a re-render. The call-order dependency on the array index explains why hooks cannot be called conditionally.

Detailed Explanation

The Key Insight:

React hooks rely on call order to associate each hook call with its stored state. When a component renders, React tracks which hook is being called using an incrementing index. The first useState call uses index 0, the second uses index 1, and so on.

This is why hooks must be called in the same order on every render — conditional or loop-based hook calls would shift the indices, causing hooks to read the wrong state.

Simplified Implementation:

The minimal implementation needs three things:

  1. A state array to persist values across renders
  2. A call index that resets to 0 before each render
  3. A setter function that updates the stored value and triggers a re-render

How Real React Differs:

  • State is stored on Fiber nodes, not in a global array. Each component instance has its own linked list of hooks.
  • Updates are batched — multiple setState calls in the same event handler result in a single re-render.
  • Setters support updater functions — setState(prev => prev + 1) uses the latest state, not the stale closure value.
  • React uses Object.is for comparison — if the new value is the same as the current value, the re-render is skipped.
  • In Concurrent Mode, renders can be interrupted and resumed, meaning state updates are queued and processed in priority order.

Why This Matters in Interviews:

This question tests whether you understand hooks at a fundamental level, not just their API. Companies like Zomato ask this specifically because it reveals:

  • Understanding of closures (the setter captures the current index)
  • Understanding of why Rules of Hooks exist (index-based tracking)
  • Understanding of React's rendering model (setState triggers re-render)

Code Examples

Simplified useState implementationJavaScript
// Module-level state storage
const stateStore = [];
let stateIndex = 0;

function useState(initialValue) {
  // Capture the current index for this hook call
  const currentIndex = stateIndex;

  // Initialize state on first render
  if (stateStore[currentIndex] === undefined) {
    stateStore[currentIndex] = initialValue;
  }

  // Create setter that captures the correct index via closure
  const setState = (newValue) => {
    stateStore[currentIndex] = newValue;
    render(); // Trigger re-render
  };

  // Advance index for the next hook call
  stateIndex++;

  return [stateStore[currentIndex], setState];
}

// Mock render function
function render() {
  stateIndex = 0; // Reset index before each render
  App();          // Re-run the component
}

// Usage — works exactly like React's useState
function App() {
  const [count, setCount] = useState(0);
  const [name, setName] = useState('World');

  console.log(`Count: ${count}, Name: ${name}`);
  // First render:  Count: 0, Name: World
  // After setCount(1): Count: 1, Name: World
}

App(); // Initial render

Real-World Applications

Use Cases

Custom Framework Development

Understanding hook internals is essential when building custom rendering frameworks or React-like libraries (Preact, Solid).

Debugging Stale Closure Bugs

Knowing how hooks store state via closure-captured indices helps diagnose stale state bugs in complex useEffect and useCallback chains.

Mini Projects

Mini React Hooks System

advanced

Implement useState, useEffect, and useRef from scratch to understand how React's hook system works internally.

Rules of Hooks Linter

advanced

Build a simple static analyzer that detects conditional hook calls in JavaScript function components.

Industry Examples

Preact

Preact implements hooks in 1.5KB using a linked-list approach similar to React's Fiber hooks, demonstrating the same index-based tracking pattern.

Meta

React's actual hook implementation uses a singly-linked list on Fiber nodes (not an array), but the index-based mental model accurately explains the ordering constraint.

Resources

React Docs - useState Reference

docs

Build your own React - Rodrigo Pombo

article

Related Questions

Implement a basic version of useEffect from scratch.

senior
hooks

Explain the useState and useEffect hooks and their common patterns.

mid
hooks
Previous
Explain React's diffing algorithm in detail. How does it achieve O(n) complexity?
Next
Implement a basic version of useEffect from scratch.
PrevNext