Created
August 30, 2019 07:02
-
-
Save n1ru4l/9f4c1e06c1653109723ecc38c224400a to your computer and use it in GitHub Desktop.
useResetState
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
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