Skip to content

Instantly share code, notes, and snippets.

@BrandonSmith
Created March 10, 2023 02:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BrandonSmith/85b8082de7bf59822c685b73a4c2163b to your computer and use it in GitHub Desktop.
Save BrandonSmith/85b8082de7bf59822c685b73a4c2163b to your computer and use it in GitHub Desktop.
useGetState
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