1

I have a custom hook which fetches some basic user profile data from my graphql server. It is called from a number of components to access that data. Right now it seems like it is causing rerenders, because it fetches that data again, each time it is called. How should I best cache this data within this hook? useCustomQuery is imported from my gql client.

export const useUserData = () => {

  const { data, isLoading, error } = useCustomQuery({
    query: async (query) => {
      return getFields(query.me, 'account_id', 'role', 'email', 'profile_image');
    },
  });
  return { isLoading, error, me: data };
};
ambe5960
  • 1,870
  • 2
  • 19
  • 47

2 Answers2

0

I would look at where you are calling your custom hook (in a useEffect maybe?), and try to incorporate useMemo to memoize the data coming back until you need to actually call that custom hook again.

But, without further code, it's a bit difficult to diagnose.

TR3
  • 327
  • 3
  • 6
-1

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

SNikhill
  • 446
  • 2
  • 8