Skip to content

Instantly share code, notes, and snippets.

@jsuryahyd
Last active July 7, 2025 19:58
Show Gist options
  • Save jsuryahyd/c0ed65003e98a1d3bea1d17ac892e7c9 to your computer and use it in GitHub Desktop.
Save jsuryahyd/c0ed65003e98a1d3bea1d17ac892e7c9 to your computer and use it in GitHub Desktop.
Simplified React `useState` implementation
/**
* Ask: Update the App component so the <h2> element gets a color
* from the COLORS array. Clicking on the Next button should cycle through the colors.
*
* Example: It should be initially blue, then red, ..., cyan, and then blue again.
*/
import ReactDOM from "react-dom";
// import { useState } from "react";
const COLORS = ["blue", "red", "green", "yellow", "black", "cyan"];
const FS = [12, 16, 18, 21];
const states = [];
export default function App() {
const [currColorIdx, setCurrentColorIdx] = useState(0, "color");
const [fs, setFs] = useState(0, "fs");
function toggleColor() {
setCurrentColorIdx((currIdx) => {
if (currIdx >= COLORS.length - 1) return 0;
return currIdx + 1;
});
}
return (
<div className="App">
<button onClick={() => toggleColor()}>Next</button>
<h2 style={{ color: COLORS[currColorIdx] }}>
Start editing to see some magic happen!
</h2>
<p>{FS[fs]}</p>
<button
onClick={() =>
setFs((currIdx) => {
if (currIdx >= FS.length - 1) return 0;
return currIdx + 1;
})
}
>
Next Font
</button>
</div>
);
}
let hooksCallIdx = -1;
function useState(initialState, debugVal) {
hooksCallIdx++;
const hookIdx = hooksCallIdx;
if (states[hookIdx] === undefined) states[hookIdx] = initialState;
function updateStateAndRerender(valOrFn) {
if (typeof valOrFn === "function") {
states[hookIdx] = valOrFn(states[hookIdx]);
} else {
states[hookIdx] = val;
}
// setTimeout(() => { //optional
hooksCallIdx = -1;
ReactDOM.render(<App />, rootElement);
// }, 10);
}
return [states[hookIdx], updateStateAndRerender];
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment