Learn the concept
Hooks
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.
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:
How Real React Differs:
setState calls in the same event handler result in a single re-render.setState(prev => prev + 1) uses the latest state, not the stale closure value.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:
// 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 renderUnderstanding hook internals is essential when building custom rendering frameworks or React-like libraries (Preact, Solid).
Knowing how hooks store state via closure-captured indices helps diagnose stale state bugs in complex useEffect and useCallback chains.
Implement useState, useEffect, and useRef from scratch to understand how React's hook system works internally.
Build a simple static analyzer that detects conditional hook calls in JavaScript function components.
Preact implements hooks in 1.5KB using a linked-list approach similar to React's Fiber hooks, demonstrating the same index-based tracking pattern.