Skip to content

Instantly share code, notes, and snippets.

@Glidias
Last active March 23, 2022 10:50
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 Glidias/802872bba5b948422d0675e3ba57e1d8 to your computer and use it in GitHub Desktop.
Save Glidias/802872bba5b948422d0675e3ba57e1d8 to your computer and use it in GitHub Desktop.
Stateful state hook that may reset itself given outside conditions
/**
* @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