React Query supports integration with React Suspense, making data fetching as natural as handling component rendering:
Basic Integration Method
-
Enable Suspense mode:
javascriptconst { data } = useQuery('todos', fetchTodos, { suspense: true, }); -
Wrap with Suspense component:
javascriptfunction TodoList() { const { data: todos } = useQuery('todos', fetchTodos, { suspense: true, }); return ( <ul> {todos.map(todo => ( <li key={todo.id}>{todo.title}</li> ))} </ul> ); } function App() { return ( <Suspense fallback={<div>Loading...</div>}> <TodoList /> </Suspense> ); }
Error Boundary Handling
When using Suspense mode, errors need to be caught through Error Boundary:
javascriptclass ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false, error: null }; } static getDerivedStateFromError(error) { return { hasError: true, error }; } render() { if (this.state.hasError) { return <div>Error: {this.state.error.message}</div>; } return this.props.children; } } function App() { return ( <ErrorBoundary> <Suspense fallback={<div>Loading...</div>}> <TodoList /> </Suspense> </ErrorBoundary> ); }
Considerations
-
Compatibility:
- Suspense mode requires React 16.6+
- Ensure all related components support Suspense
-
Error Handling:
- Must use Error Boundary to catch errors
- Can no longer use error and isError properties returned by useQuery
-
Cache Behavior:
- Even if data is in cache, Suspense is still triggered on first render
- Subsequent renders will directly use cached data without triggering Suspense
-
Performance Considerations:
- Suspense mode may cause multiple renders of the component tree
- For complex applications, need to balance user experience and performance
-
Compatibility with Other Features:
- Window focus refetching: May cause unexpected Suspense triggers
- Polling: Need to be carefully configured to avoid frequent Suspense triggers
-
Server-Side Rendering:
- Using Suspense in SSR environment requires special handling
- Recommended to use
dehydrateandhydratemethods
Best Practices
-
Progressive Adoption:
- Try Suspense mode in non-critical components first
- Gradually expand to the entire application
-
Reasonable Use of Fallback:
- Provide meaningful loading states
- Avoid using overly simple loading indicators
-
Combine with Prefetching:
- Use
queryClient.prefetchQueryto get data in advance - Reduce the number of Suspense triggers
- Use
-
Error Boundary Strategy:
- Place Error Boundary at appropriate levels
- Provide specific error messages and recovery options
By properly integrating React Query and Suspense, you can create more fluid, responsive user interfaces while maintaining code simplicity and readability.