Skip to content

Instantly share code, notes, and snippets.

@saintplay
Created September 30, 2023 03:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saintplay/89d70086c3d804f9e29f85dcf2ef9cb7 to your computer and use it in GitHub Desktop.
Save saintplay/89d70086c3d804f9e29f85dcf2ef9cb7 to your computer and use it in GitHub Desktop.
useRefState.ts
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