Skip to content

Instantly share code, notes, and snippets.

@hawx1993
Created June 12, 2022 13:08
Show Gist options
  • Select an option

  • Save hawx1993/c1947e1be25659e350f239437ebfc14d to your computer and use it in GitHub Desktop.

Select an option

Save hawx1993/c1947e1be25659e350f239437ebfc14d to your computer and use it in GitHub Desktop.
import { SetStateAction, useCallback, useEffect, useRef, useState } from 'react';
type Callback<T> = (value?: T) => void;
type DispatchWithCallback<T> = (value: T, callback?: Callback<T>) => void;
function useStateCallback<T>(initialState: T | (() => T)): [T, DispatchWithCallback<SetStateAction<T>>] {
const [state, _setState] = useState(initialState);
const callbackRef = useRef<Callback<T>>();
const isFirstCallbackCall = useRef<boolean>(true);
const setState = useCallback((setStateAction: SetStateAction<T>, callback?: Callback<T>): void => {
callbackRef.current = callback;
_setState(setStateAction);
}, []);
useEffect(() => {
if (isFirstCallbackCall.current) {
isFirstCallbackCall.current = false;
return;
}
callbackRef.current?.(state);
}, [state]);
return [state, setState];
}
export default useStateCallback;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment