#Difference between throwing and returning redirects

1 messages · Page 1 of 1 (latest)

bleak light
#

Totally non-critical, but I was wondering about the difference between throw redirect and return redirect in a loader

According to the docs (https://remix.run/docs/en/main/utils/redirect):

you can throw redirects to break through the call stack and redirect right away

What I assumed this meant was that if any loader throws a redirect, any other loaders will stop running and the redirect will happen at once.

However I've just tested this with two loaders and in fact what happens is that both loaders run in full, both throw redirects, and then remix picks the first redirect according to the hierarchy of the loaders - rather than the order of the throws. Which seems to be the same behaviour as just returning the redirect.

So, what's the actual difference?

Follow-up questions: what if you did want to redirect early? Or what if you want the redirect from the leaf loader to be used rather than a parent loader?

midnight hedge
#

functionally the same, main advantages to throwing are

  • you can throw a response/redirect from a helper function like const user = await requireUser() so you don't have to check the response type just to return a redirect in every loader
  • when you return something, it affects the type inference on the loader. If you throw, it skips that, which makes it easy for the useLoaderData<typeof loader> hook to get the real loader data it's going to see