A custom React Hook is a way to abstract a piece of stateful logic and every component that ends up calling this hook gets a separate instance of the hook along with a separate isolated state.
For Example:
If you call useUserData
from:
UserProfile
component and
UserAccountSettings
component
Both of them would call useUserData
and none of them would be aware that the other component already performed a fetch using this hook.
And if useUserData
had an internal state then, both of the useUserData
invocations (one from UserProfile
and the other from UserAccountSettings
) would end up getting a separate and independent state.
What if you want to maintain a cache?
Yes, you can do that. You just need to store data
returned from the GraphQL server in an external scope like a Redux Store, a Global Context or even a parent component's state.
But, you should not handle this storing/caching
logic in useUserData
instead, it needs to be abstracted out. Perhaps, it can be part of the handler making the request to the server.
Why can't the hook be responsible for caching?
A hook can be responsible for it and you can take an approach where you maintain a cache by defining a variable in the scope external to the hook's lifecycle.
It will still work.
In the end, it depends upon your coding pattern and the level of abstraction you want.
Why can't UserProfile or UserAccountSettings perform the cache check?
Because that would lead to a conditional check and hence, a conditional call to the useUserData
and a React hook should not be called conditionally.
Resources