TanStackT
TanStack3y ago
18 replies
clean-aquamarine

React Query Infinite Re-Rerender

Hello,

I'm noticing a weird behavior with my code. I'm pretty certain I'm doing something wrong, I'm just not sure what.

type UseServerStoreProps<Data> = {
  name: string;
  itemId: string;
  getFn: () => Promise<Data>;
  demoData: Data;
};

export function useServerStore<Data>(props: UseServerStoreProps<Data>) {
  const { name, itemId, getFn, demoData } = props;
  const demo = useDemo();
  const user = useUser();

  const userId = useMemo(() => {
    if (demo.isDemo) return 'demo';
    if (!user.data.user) throw new Error('useServerStore called without user');
    return user.data.user.id;
  }, [demo.isDemo, user.data.user]);

  const queryKey = ['store', name, userId, itemId, 'server'];

  const query = useQuery({
    queryKey,
    async queryFn() {
      if (demo.isDemo) return demoData;
      return getFn();
    },
    suspense: true,
    meta: storeMeta,
    networkMode: 'offlineFirst',
    staleTime: isDev ? ms('1 minute') : ms('1 day'),
    cacheTime: ms('30 days'),
    // enabled: false,
  });

  // ...

  if (!query.data) throw new Error('suspense not triggered');

  return {
    data: query.data,
    query,
  };
}


The gist of what is going on is that I have a hook to fetch some data from the server and cache it locally. That works great! Now I'm trying to add a demo mode so that a user can play around with some mock data before signing into the product. For some reason, the second I add if (demo.isDemo) return demoData;, I start to get infinite re-renders. Removing the line immediately fixes it, adding it back breaks it again.

I am using things like the persist plugins, and actually noticed that it's constantly writing to the localStorage (the timestamp increases). However inspecting the items, the dataUpdateCount is a super low number.

Any obvious ideas as to what is going on?
Was this page helpful?