Skip to content

Instantly share code, notes, and snippets.

@amerllica
Last active June 21, 2021 11:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amerllica/985504bc41edf70d0a01c9b40e4c80c0 to your computer and use it in GitHub Desktop.
Save amerllica/985504bc41edf70d0a01c9b40e4c80c0 to your computer and use it in GitHub Desktop.
ReactJS hook for passing state and a setter function with ability of getting callback for each setter call.
import { useRef, useCallback, useEffect, useState } from 'react';
import type { Dispatch, SetStateAction } from 'react';
type StateFunctionType<S> = Dispatch<SetStateAction<S | undefined>>;
type SetStateCallbackGeneric<S> = (
x: S | StateFunctionType<S>,
cb?: Function
) => void;
const useStateCallback = <T>(
initialState: T
): [T, SetStateCallbackGeneric<T>] => {
const [state, setState] = useState<T>(initialState);
const cbRef = useRef(null);
const setStateCallback = useCallback((newState, cb) => {
cbRef.current = cb;
setState(newState);
}, []);
useEffect(() => {
if (typeof cbRef?.current === 'function') {
cbRef?.current?.(state);
cbRef.current = null;
}
}, [state]);
return [state, setStateCallback];
};
export default useStateCallback;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment