T
TanStack8mo ago
xenophobic-harlequin

synchronous state with query? is this ok?

i've typically heard react query referred to as an async state manager, in addition to server state my questin is, is there anything inherently wrong with using it for synchronous state, for the sake of keeping the code style/toolchain consistent? i have a one big piece of data that my whole application needs access to, and i need to initialize it when its provider mounts. previously i was just useEffect(() => ..., []) and setting the value with useState in there i've modified it now to do this. this isn't async nor server state- is there any footguns here i need to be aware of, or anything simply incorrect?
const zeroQueryOptions = (userId: string, getToken: () => Promise<string>) =>
queryOptions({
queryKey: ["zero"],
queryFn: () => {
return createZero(userId, getToken); // create zero client
},
});

export const ZeroProvider = (props: PropsWithChildren) => {
const auth = useAuthentication();
const zeroQuery = useQueryTanstack(
zeroQueryOptions(auth.user.id, auth.getAccessToken)
);

if (zeroQuery.status === "pending") return null;

if (zeroQuery.status === "error") return <div>Issue syncing data, please try again later</div>;

return (
<ZeroProviderInternal zero={zeroQuery.data}>{props.children}</ZeroProviderInternal>
);
};
const zeroQueryOptions = (userId: string, getToken: () => Promise<string>) =>
queryOptions({
queryKey: ["zero"],
queryFn: () => {
return createZero(userId, getToken); // create zero client
},
});

export const ZeroProvider = (props: PropsWithChildren) => {
const auth = useAuthentication();
const zeroQuery = useQueryTanstack(
zeroQueryOptions(auth.user.id, auth.getAccessToken)
);

if (zeroQuery.status === "pending") return null;

if (zeroQuery.status === "error") return <div>Issue syncing data, please try again later</div>;

return (
<ZeroProviderInternal zero={zeroQuery.data}>{props.children}</ZeroProviderInternal>
);
};
2 Replies
protestant-coral
protestant-coral8mo ago
yeah a ton actually: - you're unnecessarily in pending state - retries are on - you have to set staleTime / gcTime or risk this automatically re-running or being garbage collected - you probably don't want structuralSharing I really wouldn't do this! you CAN get it right but really, zustand is about 1kb and so much better for this
xenophobic-harlequin
xenophobic-harlequinOP8mo ago
Awesome, thank you for the info!

Did you find this page helpful?