From 0bdbef7f158d43d3e071fafc583639b54901bcc7 Mon Sep 17 00:00:00 2001 From: Matt Brophy Date: Mon, 4 Mar 2024 11:03:58 -0500 Subject: [PATCH] Add note to docs on layout useLoaderData restriction (#8958) Co-authored-by: houmark --- docs/file-conventions/root.md | 50 +++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/docs/file-conventions/root.md b/docs/file-conventions/root.md index 65eb4ea8543..16b2de4f8eb 100644 --- a/docs/file-conventions/root.md +++ b/docs/file-conventions/root.md @@ -146,6 +146,56 @@ export function ErrorBoundary() { } ``` +**A note on `useLoaderData`in the `Layout` Component** + +`useLoaderData` is not permitted to be used in `ErrorBoundary` components because it is intended for the happy-path route rendering, and its typings have a built-in assumption that the `loader` ran successfully and returned something. That assumption doesn't hold in an `ErrorBoundary` because it could have been the `loader` that threw and triggered the boundary! In order to access loader data in `ErrorBoundary`'s, you can use `useRouteLoaderData` which accounts for the loader data potentially being `undefined`. + +Because your `Layout` component is used in both success and error flows, this same restriction holds. If you need to fork logic in your `Layout` depending on if it was a successful request or not, you can use `useRouteLoaderData("root")` and `useRouteError()`: + +```tsx filename="app/root.tsx" lines=[6-7,19-29,32-34] +export function Layout({ + children, +}: { + children: React.ReactNode; +}) { + const data = useRouteLoaderData("root"); + const error = useRouteError(); + + return ( + + + + + + +