T
TanStack2y ago
deep-jade

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,
};
};
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>
const { isAuthenticated } = useAuthState();

<Header>
{isAuthenticated && <Profile />
</Header>
what would you guys recommend?
1 Reply
absent-sapphire
absent-sapphire2y ago
Splitting the app at the top level into authenticated and unauthenticated will likely be a bit less code to manage

Did you find this page helpful?