React Query provides several methods to invalidate cached data, triggering new data fetches. Here are some common strategies:
-
Automatic Refetching: React Query automatically refetches data in specific scenarios, such as when the window regains focus or the network reconnects. This behavior is controlled by the configuration options
refetchOnWindowFocusandrefetchOnReconnect. -
Stale Time: By configuring the
staleTimeoption, you can specify how long data remains valid before it becomes 'stale'. Once data is stale, any query for this data will trigger a refetch.
jsxuseQuery('todos', fetchTodos, { staleTime: 5000, });
In this example, fetchTodos is a function that fetches todo data. The data is considered stale after 5 seconds, and if the component re-renders or a new request is made, React Query will refetch the data.
- Manual Refetching: You can manually trigger data refetching using the
refetchfunction returned byuseQuery.
jsxconst { data, refetch } = useQuery('todos', fetchTodos); // Call refetch on an interaction or event // For example, a button click <button onClick={() => refetch()}>Reload</button>
- Invalidation: React Query's
invalidateQueriesfunction can invalidate specific queries or all query data, triggering a refetch. This is typically used after data changes, such as after form submissions or data updates.
jsxconst queryClient = useQueryClient(); // Assume 'todos' is the key for the query to invalidate queryClient.invalidateQueries('todos');
For example, if you have a feature to add a new todo, you might invalidate the todo list cache after adding to ensure it's up-to-date.
- Optimistic Updates: When performing data modification operations (such as updates or deletions), you can first update the cached data, then execute asynchronous operations. If the operation fails, you can roll back the cached data. This advanced strategy enhances user experience by making the interface more responsive.
jsxconst queryClient = useQueryClient(); queryClient.setQueryData('todos', old => { // Assume we're adding a new todo return [...old, newTodo]; }); // Then send the request to the server // If the request fails, roll back the cached data
These are some basic methods React Query uses to handle cached data invalidation. Typically, you can choose the appropriate strategies based on your application's needs or combine them as needed.