Created
June 12, 2022 13:08
-
-
Save hawx1993/c1947e1be25659e350f239437ebfc14d 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 { 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