Last active
September 8, 2025 13:27
-
-
Save harbirchahal/d267f28fd06f54d7a4796cc4bd99f171 to your computer and use it in GitHub Desktop.
React | Reimplementing useState hook
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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> | |
| ); | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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