TLDR; Suspense in react-query

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

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post
teledyne-flir-ai-enabled-neutrino-ground-isr-imaging-module

Teledyne FLIR AI-Enabled Neutrino Ground ISR Imaging Module

Next Post
the-8-hour-debug:-how-a-silly-mistake-cost-me-a-day

The 8-Hour Debug: How a Silly Mistake Cost Me a Day

Related Posts

瀏覽器跑 LLM 的實際體感與骨感限制

直接在瀏覽器跑 LLM,既兼顧隱私又不用複雜的GPU設定,太完美了吧? 從 WebLLM 到 Transformers.js,前端社群有一群反骨仔吹起一股「邊緣 LLM」的熱潮,可是,當真正將模型落地到使用者的瀏覽器時,第一個面對的考驗就是,WebGPU 真的有比 WASM 快嗎? 這陣子實測的結論比想像中更加戲劇化, 500M 以下的微型模型,WASM 反而快了 12%,但是對於 3B 以上的大模型,WASM 直接變成悲劇,直接讓Chrome撞的頭破血流(Chrome…
Read More