Avoid refetching when a requested date range is already covered by cached data

2 weeks ago 17
ARTICLE AD BOX

I have a calendar component that fetches event data from my backend using TanStack Query, based on a date range. The calendar supports three views: month, week, and day.

On initial load, the component fetches events for the month view. When the user switches views or navigates the calendar, the date range changes and a new query is triggered.

The problem is that the component often refetches data for a date range that is fully contained within a previously fetched range. For example, after fetching the full month, switching to a week or day view inside that same month still triggers a new request—even though the data already exists in the cache.

I’m looking for a way to structure or configure TanStack Query so that it can reuse cached data when the requested range is a subset of an existing range, instead of making another network request.

I considered extracting and manually managing date ranges in separate state, but that feels like it defeats the purpose of TanStack Query’s cache and would be hard to maintain long-term. Ideally, I’d like the query configuration or cache behavior itself to handle this.

Current implementation:

// Calendar client component const [calendarRange, setCalendarRange] = useDateRange(); // custom reducer hook const { data: todos } = useCalendarTodo(calendarRange); return ( <DnDCalendar events={todos} onRangeChange={setCalendarRange} /> ); // TanStack Query hook export const useCalendarTodo = (calendarRange: { start: Date; end: Date }) => { return useQuery({ queryKey: [ "calendarTodo", calendarRange.start.getTime(), calendarRange.end.getTime(), ], queryFn: async () => { return api.GET({ url: `/api/calendar/todo?start=${calendarRange.start.getTime()}&end=${calendarRange.end.getTime()}`, }); }, }); };

What I’m trying to achieve:

Fetch a larger range (e.g. a month) once

Reuse that cached data for smaller ranges (week/day) that fall within it

Avoid duplicate or unnecessary network requests

Keep the solution aligned with TanStack Query’s intended patterns

Is there a recommended way to model query keys, cache data, or query behavior in TanStack Query to support this use case?

Note: I’m using a useReducer instead of useState to manage the date range because react-big-calendar emits different range shapes depending on the view. The reducer normalizes this so the range always has start and end properties.

Read Entire Article