Created
February 24, 2022 10:38
-
-
Save bedekelly/3700ed23d9aa18359ead77d4716790f0 to your computer and use it in GitHub Desktop.
Reactive state coupled with an immediately-updating ref
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 { 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