Last active
January 8, 2022 10:29
-
-
Save Harshmakadia/ef640bc1e65443e801fa4b24b3ec1b1f to your computer and use it in GitHub Desktop.
useStateCallback
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 App = () => { | |
const [state, setState] = useStateCallback(0); // same API as useState + setState with cb | |
const handleClick = () => { | |
setState( | |
prev => prev + 1, | |
// 2nd argument is callback , `s` is *updated* state | |
// Hey that state is set successfully what do you | |
// want to do, I'm callback your friend 😄 | |
s => console.log("I am called after setState, state:", s) | |
); | |
}; | |
return <button onClick={handleClick}>Increment</button>; | |
} |
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
function useStateCallback(initialState) { | |
const [state, setState] = useState(initialState); | |
const cbRef = useRef(null); | |
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