Created
September 30, 2023 03:05
-
-
Save saintplay/89d70086c3d804f9e29f85dcf2ef9cb7 to your computer and use it in GitHub Desktop.
useRefState.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 { useEffect, useState, useRef, useCallback } from 'react'; | |
export default function useRefState<TValue>(initialState: TValue) { | |
const [state, setInnerState] = useState(initialState); | |
const ref = useRef(initialState); | |
const setState = useCallback((value: TValue) => { | |
setInnerState(value); | |
ref.current = value; | |
}, []); | |
useEffect(() => { | |
ref.current = state; | |
}, [state]); | |
return [state, setState, ref] as const; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment