Created
March 10, 2023 02:07
-
-
Save BrandonSmith/85b8082de7bf59822c685b73a4c2163b to your computer and use it in GitHub Desktop.
useGetState
This file contains 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 { useMemo, useReducer, useRef } from "react"; | |
const useGetState = (initialState) => { | |
const state = useRef(initialState); | |
const [, update] = useReducer(num => ((num + 1) % 1_000_000), 0); | |
return useMemo(() => ([ | |
() => state.current, | |
(newState) => { | |
state.current = newState; | |
update(); | |
} | |
]), [update]); | |
} | |
function Game() { | |
const [count, setCount] = useGetState(0); | |
const [started, setStarted] = useGetState(false); | |
function increment() { | |
setCount(count() + 1); | |
} | |
function start() { | |
if (!started()) setTimeout(() => console.log(`Your score was ${count()}!`), 5000); | |
setStarted(true); | |
} | |
return ( | |
<button | |
onClick={() => { | |
increment(); | |
start(); | |
}} | |
> | |
{started() ? "Current score: " + count() : "Start"} | |
</button> | |
); | |
} | |
// Tells React to attach the HelloWorld component to the 'root' HTML div | |
ReactDOM.render(<Game />, document.getElementById("root")) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment