-
Notifications
You must be signed in to change notification settings - Fork 16
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
useSingleton
will execute multiple times on falsey values
#22
Comments
I like the idea of the const playerRef = useSingleton(() => new APlayer()) Also, with the current behavior, it is possible to conditionally create the instance: const [shouldLoad, setShouldLoad] = useState(false);
const instance1Ref = useSingleton(() => {
shouldLoad ? new APlayer() : null
});
const instance2Ref = useSingleton(() => {
props.foo ? new Foo() : null
}); |
It's not really about the use case (of course there are use cases), it's about the API behaving in surprising and undocumented ways. Example use cases:
(In my own code, this function is actually called |
Why not add a new ref to determine if it has been initialized? export const useSingleton = <T>(initializor: () => T): SingletonRefObject<T> => {
const initialized = useRef(false);
const r = useRef<T>();
if (!initialized.current) {
r.current = initializor();
initialized.current = true;
}
return r;
}; |
That works, but is less efficient and doubles the clutter in the React debug panel. |
Edit: I was. |
The check in the source code is
!r.current
which will trigger the function every call when the value happens to be 0, "", undefined, null etc.Here's a more universal implementation:
(technically,
EMPTY
can just be{} as const
ifSymbol
support is unavailable)An alternative is to add a
<T extends object>
type constraint, although that seems slightly unintuitive.The text was updated successfully, but these errors were encountered: