Skip to content

Instantly share code, notes, and snippets.

@satyam4p
Last active July 21, 2024 13:04
Show Gist options
  • Save satyam4p/ee71d58037dc7393322f81cc675e9327 to your computer and use it in GitHub Desktop.
Save satyam4p/ee71d58037dc7393322f81cc675e9327 to your computer and use it in GitHub Desktop.
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