Skip to content

Instantly share code, notes, and snippets.

@bedekelly
Created February 24, 2022 10:38
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 bedekelly/3700ed23d9aa18359ead77d4716790f0 to your computer and use it in GitHub Desktop.
Save bedekelly/3700ed23d9aa18359ead77d4716790f0 to your computer and use it in GitHub Desktop.
Reactive state coupled with an immediately-updating ref
import { MutableRef, useCallback, useRef, useState } from "preact/hooks";
type RefState<T> = [MutableRef<T>, T, (newVal: T) => void];
export default function useRefState<T>(initialValue: T): RefState<T> {
const ref = useRef<T>(initialValue);
const [value, setValue] = useState(initialValue);
const setValueAndUpdateRef = useCallback((value: T) => {
ref.current = value;
setValue(value);
}, []);
return [ref, value, setValueAndUpdateRef];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment