DEV Community

Cover image for TLDR; Suspense in react-query
Chaudhry Talha 🇵🇸
Chaudhry Talha 🇵🇸

Posted on

TLDR; Suspense in react-query

In React Query, Suspense is a way to handle loading states for asynchronous data fetching. It essentially lets your components "pause" until the data they need is available. For example if your data is bing fetched react loads a temporary component instead until the data becomes available.

Note: Suspense requires React 18 or later.

Without Suspense:

  • You typically use a state variable (e.g., isLoading) to indicate if data is being fetched.
  • You conditionally render loading indicators while the data is being fetched.
  • This can lead to a lot of conditional logic and potentially messy code.

With Suspense:

  • Wrap your component in a Suspense boundary: This signals to React that your component might need to wait for data.
  • Use useQuery: This hook fetches data asynchronously and provides information about the data fetching state (loading, error, data).
  • React Query throws a promise: When data is being fetched, useQuery internally throws a promise. This "suspends" rendering.
  • Suspense boundary catches the promise: The Suspense boundary catches the promise thrown by useQuery and renders a fallback component (e.g., a loading indicator) while the data is being fetched.
  • Data arrives and rendering resumes: Once the promise resolves with the data, React continues rendering your component with the actual data.

Benefits of Suspense:

  • Cleaner code: You avoid repetitive conditional logic for loading states.
  • Improved user experience: Users see a clear loading indicator while data is being fetched.

React Query and Suspense work together seamlessly:

  • React Query manages data fetching and provides the "suspending" behavior.
  • You can use Suspense boundaries to handle loading states in a cleaner way.

Code example:
https://tanstack.com/query/v5/docs/framework/react/examples/suspense

Top comments (0)