Created
November 27, 2020 15:48
-
-
Save RolandWarburton/61b1c7fd3a48fbd66f869e62bebf7e95 to your computer and use it in GitHub Desktop.
found this
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
// 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