Skip to content

Instantly share code, notes, and snippets.

@n1ru4l
Created August 30, 2019 07:02
Show Gist options
  • Save n1ru4l/9f4c1e06c1653109723ecc38c224400a to your computer and use it in GitHub Desktop.
Save n1ru4l/9f4c1e06c1653109723ecc38c224400a to your computer and use it in GitHub Desktop.
useResetState
const NO_VALUE_SYMBOL = Symbol("USE_RESET_STATE_NO_VALUE");
const useResetState = (createValue, deps = []) => {
const [, triggerRerender] = useState(createValue);
const stateRef = useRef(NO_VALUE_SYMBOL);
const depsRef = useRef(deps);
if (stateRef.current === NO_VALUE_SYMBOL) {
stateRef.current = createValue();
}
if (depsRef.current.some((value, index) => value !== deps[index])) {
depsRef.current = deps;
stateRef.current = createValue();
}
const setState = useCallback(
newState => {
if (typeof newState === "function") {
stateRef.current = newState(stateRef.current);
} else {
stateRef.current = newState;
}
triggerRerender(i => i + 1);
},
[triggerRerender]
);
return [stateRef.current, setState];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment