Skip to content

Instantly share code, notes, and snippets.

@amerllica
Last active November 5, 2024 21:48
Show Gist options
  • Select an option

  • Save amerllica/985504bc41edf70d0a01c9b40e4c80c0 to your computer and use it in GitHub Desktop.

Select an option

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 isFunction from 'lodash.isfunction';
import type {SetStateAction} from 'react';
type CallbackGeneric<S> = (newState: S) => void;
export type SetStateCallbackGeneric<S> = (
x: SetStateAction<S>,
cb?: CallbackGeneric<S>,
) => void;
const useStateCallback = <T>(
initialState?: T,
): [T, SetStateCallbackGeneric<T>] => {
const [state, setState] = useState(initialState);
const cbRef = useRef<any>();
const setStateCallback: SetStateCallbackGeneric<T> = useCallback(
(newState, cb) => {
cbRef.current = cb;
setState(newState as T);
},
[],
);
useEffect(() => {
if (isFunction(cbRef?.current)) {
cbRef?.current(state);
cbRef.current = undefined;
}
}, [state]);
return [state as T, setStateCallback];
};
export {useStateCallback};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment