Skip to content

Instantly share code, notes, and snippets.

@fostyfost
Created April 19, 2022 19:46
Show Gist options
  • Save fostyfost/52088c7973fee65ca85121438481088c to your computer and use it in GitHub Desktop.
Save fostyfost/52088c7973fee65ca85121438481088c to your computer and use it in GitHub Desktop.
React lazy ref
import type { MutableRefObject } from 'react'
import { useRef } from 'react'
const noop = {}
export function useLazyRef<T>(init: () => T) {
const ref = useRef<T | typeof noop>(noop)
if (ref.current === noop) {
ref.current = init()
}
return ref as React.MutableRefObject<T>
}
import type { MutableRefObject } from 'react'
import { useRef } from 'react'
const noop = Symbol('noop')
export function useLazyRef<T>(init: () => T) {
const lazyRef = useRef<T | typeof noop>(noop)
if (lazyRef.current === noop) {
lazyRef.current = init()
}
return lazyRef as MutableRefObject<T>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment