Skip to content

Instantly share code, notes, and snippets.

@harbirchahal
Last active September 8, 2025 13:27
Show Gist options
  • Select an option

  • Save harbirchahal/d267f28fd06f54d7a4796cc4bd99f171 to your computer and use it in GitHub Desktop.

Select an option

Save harbirchahal/d267f28fd06f54d7a4796cc4bd99f171 to your computer and use it in GitHub Desktop.
React | Reimplementing useState hook
import useCustomState from "./useState";
export default function App() {
const [likes, setLikes] = useCustomState(0);
const [dislikes, setDislikes] = useCustomState(0);
return (
<Flex gap="small">
<Button
icon={<LikeOutlined />}
onClick={() => setLikes(likes + 1)}>
{likes}
</Button>
<Button
icon={<DislikeOutlined />}
onClick={() => setDislikes(dislikes + 1)}>
{dislikes}
</Button>
</Flex>
);
}
import renderApp from "./render"
let hookStates = []
let hookIndex = 0
export default function useCustomState(initialState) {
const index = hookIndex++
if (hookStates[index] === undefined) {
hookStates[index] = initialState
}
const setState = (newState) => {
hookStates[index] = newState
// Important
hookIndex = 0
renderApp()
}
return [hookStates[index], setState]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment