乐闻世界logo
搜索文章和话题

How to integrate React Query with React Suspense, and what are the considerations?

3月7日 12:25

React Query supports integration with React Suspense, making data fetching as natural as handling component rendering:

Basic Integration Method

  1. Enable Suspense mode:

    javascript
    const { data } = useQuery('todos', fetchTodos, { suspense: true, });
  2. Wrap with Suspense component:

    javascript
    function 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:

javascript
class 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

  1. Compatibility:

    • Suspense mode requires React 16.6+
    • Ensure all related components support Suspense
  2. Error Handling:

    • Must use Error Boundary to catch errors
    • Can no longer use error and isError properties returned by useQuery
  3. 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
  4. Performance Considerations:

    • Suspense mode may cause multiple renders of the component tree
    • For complex applications, need to balance user experience and performance
  5. Compatibility with Other Features:

    • Window focus refetching: May cause unexpected Suspense triggers
    • Polling: Need to be carefully configured to avoid frequent Suspense triggers
  6. Server-Side Rendering:

    • Using Suspense in SSR environment requires special handling
    • Recommended to use dehydrate and hydrate methods

Best Practices

  1. Progressive Adoption:

    • Try Suspense mode in non-critical components first
    • Gradually expand to the entire application
  2. Reasonable Use of Fallback:

    • Provide meaningful loading states
    • Avoid using overly simple loading indicators
  3. Combine with Prefetching:

    • Use queryClient.prefetchQuery to get data in advance
    • Reduce the number of Suspense triggers
  4. 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.

标签:React