Skip to content

Instantly share code, notes, and snippets.

@RolandWarburton
Created November 27, 2020 15:48
Show Gist options
  • Save RolandWarburton/61b1c7fd3a48fbd66f869e62bebf7e95 to your computer and use it in GitHub Desktop.
Save RolandWarburton/61b1c7fd3a48fbd66f869e62bebf7e95 to your computer and use it in GitHub Desktop.
found this
// TODO study this thing
// https://stackoverflow.com/questions/54954091/how-to-use-callback-with-usestate-hook-in-react
function useSearchFilterCallback(initialState) {
const [state, setState] = useState(initialState);
const cbRef = useRef(null); // mutable ref to store current callback
const setStateCallback = (state, cb) => {
cbRef.current = cb; // store passed callback to ref
setState(state);
};
useEffect(() => {
// cb.current is `null` on initial render, so we only execute cb on state *updates*
if (cbRef.current) {
cbRef.current(state);
cbRef.current = null; // reset callback after execution
}
}, [state]);
return [state, setStateCallback];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment