Last active
November 5, 2024 21:48
-
-
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.
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 {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