Created
April 30, 2021 18:56
-
-
Save orenmizr/3af3dc4a771ebb7bcde765c16d7df0bb to your computer and use it in GitHub Desktop.
useStateCallback.js
This file contains 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
import { useState, useEffect, useRef, useCallback } from 'react'; | |
export default (initialState) => { | |
const [state, setState] = useState(initialState); | |
const cbRef = useRef(null); | |
const setStateCallback = useCallback((state, cb) => { | |
cbRef.current = cb; | |
setState(state); | |
}, []); | |
useEffect(() => { | |
if (cbRef.current) { | |
cbRef.current(state); | |
cbRef.current = null; | |
} | |
}, [state]); | |
return [state, setStateCallback]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment