Last active
May 30, 2022 03:47
-
-
Save Codennnn/2ce53e41e1c7060edc1acb5f555064b4 to your computer and use it in GitHub Desktop.
两种比较好的方式让 useRef 按需初始值,适用于有条件地调用 ref 或者生成初始值的花销很大的情景。代码来源:https://blog.thoughtspile.tech/2021/11/30/lazy-useref/。
This file contains 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
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 | |
} |
This file contains 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
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