What's the behaviour of defer
and why should I use it?
#10538
-
What does using const someLoader = () => {
return { users: fetch("/api/userList") }
}
const someDeferredLoader = () => {
return defer({ users: fetch("/api/userList") })
} Both of these loaders seem to be usable interchangeably in the component, and I haven't found out how they differ: export default function UserList() {
const { users } = useLoaderData();
return (
<React.Suspense
fallback={<p>Loading users...</p>}
>
<Await
resolve={users}
errorElement={
<p>Error loading users!</p>
}
>
{(users) => (
<p>User list...</p>
)}
</Await>
</React.Suspense>
)
} |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
Yeah i'm baffled also |
Beta Was this translation helpful? Give feedback.
-
The underlying technical difference is largely negligible and you can mostly just ignore Basically, the functional difference is that With a raw promise, at render time we have no way to know if the promise has already been resolved, so when your component renders we have to hook onto With We will very likely be deprecating |
Beta Was this translation helpful? Give feedback.
The underlying technical difference is largely negligible and you can mostly just ignore
defer
in React Router client-side only SPA's. It's required in Remix (until the single fetch feature lands) as a way to tell us that we need to serialize a promise over the wire - but in RR SPA's there's no "over the wire" so a raw promise works just fine.Basically, the functional difference is that
defer
wraps the promises so that if they resolve before we render, we can avoid an unnecessary additional render pass.With a raw promise, at render time we have no way to know if the promise has already been resolved, so when your component renders we have to hook onto
.then
andthrow data.users
fromAwait
…