Created
April 19, 2022 19:46
-
-
Save fostyfost/52088c7973fee65ca85121438481088c to your computer and use it in GitHub Desktop.
React lazy 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 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> | |
} |
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 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