Last active
March 23, 2022 10:50
-
-
Save Glidias/802872bba5b948422d0675e3ba57e1d8 to your computer and use it in GitHub Desktop.
Stateful state hook that may reset itself given outside conditions
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
/** | |
* @param callback Important: A *Memomized* callback reference (eg. via `useCallback()`) or a *Permanent* function | |
* to process/return a given lazy initialized state! | |
* State will re-update on next frame via useEffect if callback method supplied is different from previous case, | |
* but on subsequent renders only. | |
* @returns The state payload consisting of [state, setState] | |
*/ | |
export function useStateByCallback<T>(callback: () => T) { | |
const payload = useState(callback); | |
const [, setVal] = payload; | |
const ref = useRef(false); | |
useEffect(() => { | |
if (ref.current) setVal(callback); | |
else ref.current = true; | |
}, [setVal, callback]); | |
return payload; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment