Last active
July 21, 2024 13:04
-
-
Save satyam4p/ee71d58037dc7393322f81cc675e9327 to your computer and use it in GitHub Desktop.
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
import { useState, useEfftect, useRef } from "react"; | |
const useStateWithcallback = (initialState) => { | |
const [state, setState] = useState(initialState); | |
const callbackRef = useRef(null); | |
const setStateWithCallback = (newState, callback) => { | |
callbackRef.current = callback; | |
setState(newState); | |
}; | |
useEffect(() => { | |
if (callbackRef.current) { | |
callbackRef.current(state); | |
callbackRef.current = null; | |
} | |
}, [state]); | |
return [state, setStateWithCallback]; | |
}; | |
export default useStateWithcallback; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment