TanStackT
TanStack2y ago
1 reply
wet-aqua

best practices for conditional fetching with React Query?

Hi everyone, im new to react query and the whole idea of letting it handle server state. I had a question regarding conditional fetching, like for example I would only want my useUser hook to attempt to fetch the user data, if they are authenticated.

I'm using Zustand for global auth state, and I add it to my useUser hook like this

export const useUser = () => {
    const { isAuthenticated } = useAuthState();

    const { data, error, isLoading, refetch } = client.me.get.useQuery(
        ["me"],
        {},
        {
            enabled: isAuthenticated,
            retry: isAuthenticated,
            staleTime: 1000 * 60 * 60,
        },
    );

    return {
        user: data?.body.data,
        error: error?.body,
        isLoading,
        refetch,
    };
};


I am a bit curious though, if this really is the best practice? like is a common approach, or should I rather only use the useUser hook in component that should only be displayed when the user is authenticated? i.e


const { isAuthenticated } = useAuthState();

<Header>
  {isAuthenticated && <Profile />
</Header>



what would you guys recommend?
Was this page helpful?