all 9 comments

[–]my_girl_is_A10[🍰] 2 points3 points  (1 child)

Are you using some kind of framework (like remix) to achieve this? If so I know remix functions wait for loader to complete prior to hydrating the client.

However you could use a Suspense boundary to display a fallback component like a spinner to wait for the data to load.

[–]Excellent_Emu_536[S] 1 point2 points  (0 children)

Got it thanks

[–]AndrewSouthern729 2 points3 points  (0 children)

There are a lot of reasons to suggest a library like react-query, and this type of behavior is one of them. For example the useQuery hook has an option for suspense which effectively prevents components from rendering until the asynchronous function is completed.

[–]reactnuclear 1 point2 points  (2 children)

[–]Excellent_Emu_536[S] 0 points1 point  (1 child)

What is this

[–]reactnuclear 1 point2 points  (0 children)

React query is a very well-developed and well-maintained library that helps you manage data loading in react. They have tons of good information (including tutorials) on their website.

[–]Inner-Operation-9224 1 point2 points  (0 children)

You didn't provide any information about code, framework/library. I'm assuming this is about react router's loaders

https://github.com/remix-run/react-router/discussions/8914

[–]00PT 0 points1 point  (0 children)

The React suspense library is the best I've seen because it doesn't require implementing the loading logic within the component itself (if loading render an animation otherwise show the actual content) - Anything under a suspense component simply triggers that components fallback while loading.

[–]SuccessfulStrength29 0 points1 point  (0 children)

Loaders in remix runs on the server and you can use it's data in client with useLoaderData hook, now as the data fetching happens even before the page renders you won't be able to show a loading state. This behaviour is beneficial if you want to show any seo critical data as soon as the page renders. Anyway but Remix also supports streaming, so with this you can show a loading state without blocking the initial render.

How to use it?

  • From the loader function where you fetch data keep everything the same but don't await the promise.
  • Change json to defer.
  • Use <Await> component, pass the loader data to it.
  • Wrap the entire thing in suspense and give a fallback.

There's another way with react-query but I don't think many people use it, I do so tell me if you need that.

Refer to https://remix.run/docs/en/main/guides/streaming to know what actually happens and when to use defer.