Skip to content

Instantly share code, notes, and snippets.

@itsMapleLeaf
Created November 7, 2019 02:16
Show Gist options
  • Select an option

  • Save itsMapleLeaf/54f5f76e9e1460c5d44642779dbab1a3 to your computer and use it in GitHub Desktop.

Select an option

Save itsMapleLeaf/54f5f76e9e1460c5d44642779dbab1a3 to your computer and use it in GitHub Desktop.
useInstanceValue - convenience for creating a one-time value for the lifetime of a component
import { useRef } from "react"
const noValue = Symbol()
export default function useInstanceValue<T>(createValue: () => T) {
const ref = useRef<T | typeof noValue>(noValue)
if (ref.current === noValue) {
ref.current = createValue()
}
return ref.current
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment