Created
June 2, 2022 05:56
-
-
Save julenwang/43f93ca24bb7a2fdd40703f52a97c310 to your computer and use it in GitHub Desktop.
useStateWithCallback.ts
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 React, { useEffect, useRef, useState } from 'react'; | |
export const useStateWithCallback = <T>( | |
initialState: T | |
): [state: T, setState: (updatedState: React.SetStateAction<T>, callback?: (updatedState: T) => void) => void] => { | |
const [state, setState] = useState<T>(initialState); | |
const callbackRef = useRef<(updated: T) => void>(); | |
const handleSetState = (updatedState: React.SetStateAction<T>, callback?: (updatedState: T) => void) => { | |
callbackRef.current = callback; | |
setState(updatedState); | |
}; | |
useEffect(() => { | |
if (typeof callbackRef.current === 'function') { | |
callbackRef.current(state); | |
callbackRef.current = undefined; | |
} | |
}, [state]); | |
return [state, handleSetState]; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment