Polyfill - useState (React)
Source: Dev.to
Simple Working JavaScript Code for useState Polyfill
// Simple useState polyfill for interview explanation (Fixed Version)
function createUseState() {
// Array to store state values across multiple "renders" of the component.
// This simulates React's internal state storage for a component.
let stateStore = [];
// Variable to track the current index for hook calls during a single render.
// This ensures each useState call maps to the same state slot every render.
let currentIndex = 0;
// The useState function, mimicking React's hook for managing state.
function useState(initialValue) {
// Capture the current index for this specific useState call.
const index = currentIndex;
// Increment currentIndex for the next useState call in this render.
currentIndex++;
// Initialise the state value at this index if it hasn't been set yet.
if (stateStore[index] === undefined) {
stateStore[index] = initialValue;
}
// Get the current state value from stateStore at this index.
const currentState = stateStore[index];
// Define the setter function to update the state at this specific index.
const setState = function (newValue) {
stateStore[index] = newValue;
console.log(`State updated to: ${newValue} at index ${index}`);
// In real React, this would trigger a re‑render automatically.
};
// Return an array with the current state value and the setter function.
return [currentState, setState];
}
// Reset the index to 0 after a render simulation.
function resetIndex() {
currentIndex = 0;
console.log('Resetting index for next render');
}
// Expose useState and resetIndex.
return { useState, resetIndex };
}
// Create an instance of useState.
const { useState, resetIndex } = createUseState();
// Simulated functional component to demonstrate state usage.
function MyComponent() {
const [count, setCount] = useState(0); // index 0
const [name, setName] = useState('Zeeshan'); // index 1
console.log('Current Count:', count);
console.log('Current Name:', name);
// Return setters so we can update state outside the render.
return { setCount, setName };
}
// ----- Simulation -----
console.log('First Call (Initial Render):');
const { setCount, setName } = MyComponent();
resetIndex();
console.log('\nUpdating State:');
setCount(1); // updates stateStore[0]
setName('John'); // updates stateStore[1]
console.log('\nSecond Call (After Update):');
MyComponent();
resetIndex();
How to Execute
In a Browser
- Open the browser’s developer tools (e.g., Chrome DevTools).
- Go to the Console tab.
- Paste the code above and press Enter.
- Observe the logs showing the initial state, the updates, and the updated state.
In Node.js
- Save the code to a file, e.g.,
simpleUseState.js. - Run it with
node simpleUseState.jsin the terminal. - The output will appear in the console.
Expected Output
First Call (Initial Render):
Current Count: 0
Current Name: Zeeshan
Resetting index for next render
Updating State:
State updated to: 1 at index 0
State updated to: John at index 1
Second Call (After Update):
Current Count: 1
Current Name: John
Resetting index for next render
Explanation of Code
Purpose – This polyfill demonstrates the core idea behind useState: storing state in a functional component, providing a setter to update that state, and preserving the order of hook calls across renders.
stateStoreholds the actual values.currentIndextracks which hook is being executed during a render, ensuring each call gets its own slot.useStatereturns the current value and a setter that mutates the corresponding slot.resetIndexmimics React’s behaviour of resetting hook indices after each render cycle.
By calling MyComponent repeatedly and resetting the index between calls, we simulate how React re‑executes a component function while keeping the same state values.
How It Works
stateStore is a simple array that holds state values. Each useState call gets a unique index based on the length of stateStore at the time of the call.
- The state is initialized the first time
useStateis called for that index. - Subsequent calls retrieve the current value.
setState updates the value at the specific index in stateStore.
- Calling
MyComponent()multiple times simulates re‑renders, showing the updated state.
Simplification – Unlike real React, there’s no render‑cycle reset or complex hook‑order tracking. This is a basic demonstration of state persistence using an array.
Key Interview Talking Points
What is useState?
Explain that it’s a React hook for managing state in functional components, allowing you to store and update values across renders.
How This Polyfill Works
Walk through the code:
- State storage – An array (
stateStore) holds each piece of state. - Indexing – Each
useStatecall receives its own slot in the array. - Updating –
setStatereplaces the value at that slot. - Re‑render simulation – Invoking the component again reads the updated value, mimicking a re‑render.
Why Simple?
Mention that this is a minimal version to illustrate the concept. Real React uses a far more complex system (fiber tree, update queues, etc.) for state and rendering.
State Persistence
Highlight that, just like in React, the state isn’t reset between calls to the component; it persists across renders.
Limitations
- No automatic re‑rendering.
- No enforcement of hook‑order rules.
- Only suitable for conceptual understanding.
This intentionally minimal example focuses on the core idea of state management for an interview. It’s easy to explain and execute, showing how state is stored and updated. If you’d like more detail or another example, let me know!
