Created
August 24, 2022 21:57
-
-
Save RyanNorooz/300c28125e99155b6055906f041544d2 to your computer and use it in GitHub Desktop.
react useState hook with callback
This file contains 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 { useEffect, useRef, useState } from 'react' | |
type OnUpdateCallback<T> = (s: T) => void | |
type SetStateUpdaterCallback<T> = (s: T) => T | |
type SetStateAction<T> = ( | |
newState: T | SetStateUpdaterCallback<T>, | |
callback?: OnUpdateCallback<T> | |
) => void | |
export function useStateEnhanced<T>(init: T): [T, SetStateAction<T>] | |
export function useStateEnhanced<T = undefined>( | |
init?: T | |
): [T | undefined, SetStateAction<T | undefined>] | |
export function useStateEnhanced<T>(init: T): [T, SetStateAction<T>] { | |
const [state, setState] = useState<T>(init) | |
const cbRef = useRef<OnUpdateCallback<T>>() | |
const setCustomState: SetStateAction<T> = (newState, callback?): void => { | |
cbRef.current = callback | |
setState(newState) | |
} | |
useEffect(() => { | |
if (cbRef.current) cbRef.current(state) | |
cbRef.current = undefined | |
}, [state]) | |
return [state, setCustomState] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment