Skip to content

Instantly share code, notes, and snippets.

@Codennnn
Last active May 30, 2022 03:47
Show Gist options
  • Save Codennnn/2ce53e41e1c7060edc1acb5f555064b4 to your computer and use it in GitHub Desktop.
Save Codennnn/2ce53e41e1c7060edc1acb5f555064b4 to your computer and use it in GitHub Desktop.
两种比较好的方式让 useRef 按需初始值,适用于有条件地调用 ref 或者生成初始值的花销很大的情景。代码来源:https://blog.thoughtspile.tech/2021/11/30/lazy-useref/。
const none = Symbol('lazyRef.Uninitialized')
export default useJitRef(init) {
const value = useRef(none)
const ref = useLazyRef(() => ({
get current() {
if (value.current === none) {
value.current = init()
}
return value.current
},
set current(v) {
value.current = v
}
}))
return ref
}
const none = Symbol('lazyRef.Uninitialized')
export default function useLazyRef(init) {
const ref = useRef(none)
if (ref.current === none) {
ref.current = init()
}
return ref
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment