Replies: 2 comments 2 replies
-
|
when select is a new function identity (like an inline function), it will re-run because it can close over values. |
Beta Was this translation helpful? Give feedback.
-
|
@TkDodo's point about inline identity is what unblocks re-runs of The approach I reach for in this shape of problem is to keep const { data: expiresAt } = useQuery({
queryKey: ['permission'],
queryFn: fetchPermission,
refetchInterval: 5_000,
select: (res) => res.permission.ends, // ISO string, pure
});
const [hasPermission, setHasPermission] = useState(
() => expiresAt ? new Date(expiresAt) > new Date() : true
);
useEffect(() => {
if (!expiresAt) return;
const ms = new Date(expiresAt).getTime() - Date.now();
if (ms <= 0) { setHasPermission(false); return; }
const id = setTimeout(() => setHasPermission(false), ms);
return () => clearTimeout(id);
}, [expiresAt]);The |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Hi! I have a question regarding the select function and its memoization.
We are polling data from an API every 5 seconds. Often, the data returned is exactly the same.
For example, we get a permission object with an expiration date:
{ "permission": { "ends": "2026-04-13T13:00:00Z" } }In our select function, we evaluate this ends date against the current time to return a boolean flag for the UI (e.g., hasPermission).
We know exactly when the time passes, so we trigger a manual refetch() exactly at that moment to update the UI:
The problem
Since the API response is structurally identical to what is already in the cache, React Query doesn't re-run the select function. Because select isn't re-evaluated, our UI doesn't know that the time has actually passed.
I am aware that select is supposed to be a pure function and shouldn't really depend on Date.now(). What is the recommended "React Query way" to handle this scenario? Is there a way to force select to recalculate, or should we derive this time-based state entirely outside of React Query?
Response is just an example - please focus on the problem 😄
Beta Was this translation helpful? Give feedback.
All reactions