Conventions

A lot of Remix APIs aren’t imported from the "remix" package, but are instead conventions and exports from your application modules. When you import from "remix", you are calling Remix, but these APIs are when Remix calls your code.

remix.config.js

This file has a few build and development configuration options, but does not actually run on your server.

  1. module.exports = {
  2. appDirectory: "app",
  3. browserBuildDirectory: "public/build",
  4. devServerPort: 8002,
  5. publicPath: "/build/",
  6. serverBuildDirectory: "build",
  7. routes(defineRoutes) {
  8. return defineRoute(route => {
  9. route("/somewhere/cool/*", "catchall.tsx");
  10. });
  11. }
  12. };

appDirectory

The path to the app directory, relative to remix.config.js. Defaults to “app”.

  1. // default
  2. exports.appDirectory = "./app";
  3. // custom
  4. exports.appDirectory = "./elsewhere";

routes

A function for defining custom routes, in addition to those already defined using the filesystem convention in app/routes. Both sets of routes will be merged.

  1. exports.routes = async (defineRoutes) => {
  2. // If you need to do async work, do it before calling `defineRoutes`, we use
  3. // the call stack of `route` inside to set nesting.
  4. return defineRoutes((route) => {
  5. // A common use for this is catchall routes.
  6. // - The first argument is the React Router path to match against
  7. // - The second is the relative filename of the route handler
  8. route("/some/path/*", "catchall.tsx")
  9. // if you want to nest routes, use the optional callback argument
  10. route("some/:path", "some/route/file.js", () => {
  11. // - path is relative to parent path
  12. // - filenames are still relative to the app directory
  13. route("relative/path", "some/other/file")
  14. });
  15. }
  16. }

browserBuildDirectory

The path to the browser build, relative to remix.config.js. Defaults to “public/build”. Should be deployed to static hosting.

publicPath

The URL prefix of the browser build with a trailing slash. Defaults to “/build/“. This is the path the browser will use to find assets.

serverBuildDirectory

The path to the server build, relative to remix.config.js. Defaults to “build”. This needs to be deployed to your server.

devServerPort

The port number to use for the dev server. Defaults to 8002.

File Name Conventions

There are a few conventions that Remix uses you should be aware of.

Special Files

  • remix.config.js: Remix uses this file to know how to build your app for production and run it in development. This file is required.
  • app/entry.server.{js,jsx,ts,tsx}: This is your entry into the server rendering piece of Remix. This file is required.
  • app/entry.client.{js,jsx,ts,tsx}: This is your entry into the browser rendering/hydration piece of Remix. This file is required.

Route Filenames

  • app/root.tsx: This is your root layout, or “root route” (very sorry for those of you who pronounce those words the same way!). It works just like all other routes: you can export a loader, action, etc.

  • app/routes/*.{js,jsx,ts,tsx,md,mdx}: Any files in the app/routes/ directory will become routes in your application. Remix supports all of those extensions.

  • app/routes/{folder}/*.tsx: Folders inside of routes will create nested URLs.

  • app/routes/{folder} with app/routes/{folder}.tsx: When a route has the same name as a folder, it becomes a “layout route” for the child routes inside the folder. Render an <Outlet /> and the child routes will appear there. This is how you can have multiple levels of persistent layout nesting associated with URLs.

  • Dots in route filenames: Adding a . in a route file will create a nested URL, but not a nested layout. Flat files are flat layouts, nested files are nested layouts. The . allows you to create nested URLs without needing to create a bunch of layouts. For example: app/routes/some.long.url.tsx will create the URL /some/long/url.

  • app/routes/index.tsx: Routes named “index” will render when the parent layout route’s path is matched exactly.

  • $param: The dollar sign denotes a dynamic segment of the URL. It will be parsed and passed to your loaders and routes.

    For example: app/routes/users/$userId.tsx will match the following URLs: users/123 and users/abc but not users/123/abc because that has too many segments. See the routing guide for more information.

    Some CLIs require you to escape the $ when creating files:

    1. touch routes/\$params.tsx

    Params can be nested routes, just create a folder with the $ in it.

  • app/routes/files/$.tsx: To add a “splat” path (some people call this a “catchall”) name the file simply $.tsx. It will create a route path pattern like files/*. You can also use this along with dot file names: app/routes/files.$.tsx.

  • app/routes/__some-layout/some-path.tsx: Prefixing a folder with __ will create a “layout route”. Layout routes are routes that don’t add anything to the URL for matching, but do add nested components in the tree for layouts. Make sure to also have __some-layout.tsx as well. For example, all of your marketing pages could share a layout in the route tree with app/routes/__marketing.tsx as the layout and then all of the child routes go in app/routes/__marketing/products.tsx and app/routes/__marketing/buy.tsx. The __marketing.tsx route won’t add any segments to the URL, but it will render when it’s child routes match.

Escaping special characters

Because some characters have special meaning, you must use our escaping syntax if you want those characters to actually appear in the route. For example, if I wanted to make a Resource Route for a /sitemap.xml, I could name the file app/routes/[sitemap.xml].tsx. So you simply wrap any part of the filename with brackets and that will escape any special characters.

Note, you could even do `app/routes/sitemap[.]xml.tsx` if you wanted to only wrap the part that needs to be escaped. It makes no difference. Choose the one you like best.

Entry Files

entry.client.tsx

Remix uses app/entry.client.tsx as the entry point for the browser bundle. This module gives you full control over the “hydrate” step after JavaScript loads into the document.

Typically this module uses ReactDOM.hydrate to re-hydrate the markup that was already generated on the server in your server entry module.

Here’s a basic example:

  1. import ReactDOM from "react-dom";
  2. import Remix from "@remix-run/react/browser";
  3. ReactDOM.hydrate(<Remix />, document);

As you can see, you have full control over hydration. This is the first piece of code that runs in the browser. As you can see, you have full control here. You can initialize client-side libraries, setup things like window.history.scrollRestoration, etc.

entry.server.tsx

Remix uses app/entry.server.tsx to generate the HTTP response when rendering on the server. The default export of this module is a function that lets you create the response, including HTTP status, headers, and HTML, giving you full control over the way the markup is generated and sent to the client.

This module should render the markup for the current page using a <RemixServer> element with the context and url for the current request. This markup will (optionally) be re-hydrated once JavaScript loads in the browser using the browser entry module.

You can also export an optional handleDataRequest function that will allow you to modify the response of a data request. These are the requests that do not render HTML, but rather return the loader and action data to the browser once client side hydration has occurred.

Here’s a basic example:

  1. import ReactDOMServer from "react-dom/server";
  2. import type {
  3. EntryContext,
  4. HandleDataRequestFunction
  5. } from "remix";
  6. import { RemixServer } from "remix";
  7. export default function handleRequest(
  8. request: Request,
  9. responseStatusCode: number,
  10. responseHeaders: Headers,
  11. remixContext: EntryContext
  12. ) {
  13. const markup = ReactDOMServer.renderToString(
  14. <RemixServer context={remixContext} url={request.url} />
  15. );
  16. responseHeaders.set("Content-Type", "text/html");
  17. return new Response("<!DOCTYPE html>" + markup, {
  18. status: responseStatusCode,
  19. headers: responseHeaders
  20. });
  21. }
  22. // this is an optional export
  23. export const handleDataRequest: HandleDataRequestFunction =
  24. (
  25. response: Response,
  26. // same args that get passed to the action or loader that was called
  27. { request, params, context }
  28. ) => {
  29. response.headers.set("x-custom", "yay!");
  30. return response;
  31. };

Route Module API

A route in Remix can be used for many things. Usually they’re used for the user interface of your app, like a React component with server-side lifecycle hooks. But they can also serve as generic routes for any kind of resource (like dynamic CSS or social images).

It’s important to read Route Module Constraints.

default export

This is the component that will render when the route matches.

  1. export default function SomeRouteComponent() {
  2. return (
  3. <div>
  4. <h1>Look ma!</h1>
  5. <p>I'm still using React after like 7 years.</p>
  6. </div>
  7. );
  8. }

loader

Each route can define a “loader” function that will be called on the server before rendering to provide data to the route.

  1. export const loader = async () => {
  2. return { ok: true };
  3. };
  4. // Typescript
  5. import type { LoaderFunction } from "remix";
  6. export const loader: LoaderFunction = async () => {
  7. return { ok: true };
  8. };

This function is only ever run on the server. On the initial server render it will provide data to the HTML document. On navigations in the browser, Remix will call the function via fetch. This means you can talk directly to your database, use server only API secrets, etc. Any code that isn’t used to render the UI will be removed from the browser bundle.

Using the database ORM Prisma as an example:

  1. import { useLoaderData } from "remix";
  2. import { prisma } from "../db";
  3. export const loader = async () => {
  4. return prisma.user.findMany();
  5. };
  6. export default function Users() {
  7. const data = useLoaderData();
  8. return (
  9. <ul>
  10. {data.map(user => (
  11. <li key={user.id}>{user.name}</li>
  12. ))}
  13. </ul>
  14. );
  15. }

Because prisma is only used in the loader it will be removed from the browser bundle.

Remix polyfills the Web Fetch API on the server so you can use fetch inside of your loader as if you were in the browser.

loader params

Route params are passed to your loader. If you have a loader at data/invoices/$invoiceId.tsx then Remix will parse out the invoiceId and pass it to your loader. This is useful for fetching data from an API or database.

  1. // if the user visits /invoices/123
  2. export const loader: LoaderFunction = ({ params }) => {
  3. params.invoiceId; // "123"
  4. };

loader request

This is a Fetch Request instance with information about the request. You can read the MDN docs to see all of it’s properties.

Most common cases are reading headers or the URL. You can also use this to read URL URLSearchParams from the request like so:

  1. export const loader: LoaderFunction = ({ request }) => {
  2. // read a cookie
  3. const cookie = request.headers.get("Cookie");
  4. // parse the search params
  5. const url = new URL(request.url);
  6. const search = url.searchParams.get("search");
  7. };

loader context

This is the context you passed in to your server adapter’s getLoadContext() function. It’s a way to bridge the gap between the adapter’s request/response API with your Remix app.

This API is an escape hatch, it’s uncommon to need it

Say your express server (or your serverless function handler) looks something like this:

  1. const {
  2. createRequestHandler
  3. } = require("@remix-run/express");
  4. app.all(
  5. "*",
  6. createRequestHandler({
  7. getLoadContext(req, res) {
  8. // this becomes the loader context
  9. return { expressUser: req.user };
  10. }
  11. })
  12. );

And then your loader can access it.

  1. export const loader: LoaderFunction = ({ context }) => {
  2. const { expressUser } = context;
  3. // ...
  4. };

Returning objects

You can return plain JavaScript objects from your loaders that will be made available to your route modules.

  1. export const loader = async () => {
  2. return { whatever: "you want" };
  3. };

Returning Response Instances

When you return a plain object, Remix turns it into a Fetch Response. This means you can return them yourself, too.

  1. export const loader: LoaderFunction = async () => {
  2. const users = await db.users.findMany();
  3. const body = JSON.stringify(users);
  4. return new Response(body, {
  5. headers: {
  6. "Content-Type": "application/json"
  7. }
  8. });
  9. };

Remix provides helpers, like json, so you don’t have to construct them yourself:

  1. import { json } from "remix";
  2. export const loader: LoaderFunction = async () => {
  3. const users = await fakeDb.users.findMany();
  4. return json(users);
  5. };

Between these two examples you can see how json just does a little of work to make your loader a lot cleaner. You usually want to use the json helper when you’re adding headers or a status code to your response:

  1. import { json } from "remix";
  2. export const loader: LoaderFunction = async ({
  3. params
  4. }) => {
  5. const user = await fakeDb.project.findOne({
  6. where: { id: params.id }
  7. });
  8. if (!user) {
  9. return json("Project not found", { status: 404 });
  10. }
  11. return json(user);
  12. };

See also:

Throwing Responses in Loaders

Along with returning responses, you can also throw Response objects from your loaders, allowing you to break through the call stack and show an alternate UI with contextual data through the CatchBoundary.

Here is a full example showing how you can create utility functions that throw responses to stop code execution in the loader and move over to an alternative UI.

  1. import { json } from "remix";
  2. import type { ThrownResponse } from "remix";
  3. export type InvoiceNotFoundResponse = ThrownResponse<
  4. 404,
  5. string
  6. >;
  7. export function getInvoice(id, user) {
  8. const invoice = db.invoice.find({ where: { id } });
  9. if (invoice === null) {
  10. throw json("Not Found", { status: 404 });
  11. }
  12. return invoice;
  13. }
  1. import { redirect } from "remix";
  2. import { getSession } from "./session";
  3. function requireUserSession(request) {
  4. const session = await getSession(
  5. request.headers.get("cookie")
  6. );
  7. if (!session) {
  8. // can throw our helpers like `redirect` and `json` because they
  9. // return responses.
  10. throw redirect("/login", 302);
  11. }
  12. return session.get("user");
  13. }
  1. import { useCatch, useLoaderData } from "remix";
  2. import type { ThrownResponse } from "remix";
  3. import { requireUserSession } from "~/http";
  4. import { getInvoice } from "~/db";
  5. import type {
  6. Invoice,
  7. InvoiceNotFoundResponse
  8. } from "~/db";
  9. type InvoiceCatchData = {
  10. invoiceOwnerEmail: string;
  11. };
  12. type ThrownResponses =
  13. | InvoiceNotFoundResponse
  14. | ThrownResponse<401, InvoiceCatchData>;
  15. export const loader = async ({ request, params }) => {
  16. const user = await requireUserSession(request);
  17. const invoice: Invoice = getInvoice(params.invoiceId);
  18. if (!invoice.userIds.includes(user.id)) {
  19. const data: InvoiceCatchData = {
  20. invoiceOwnerEmail: invoice.owner.email
  21. };
  22. throw new json(data, { status: 401 });
  23. }
  24. return invoice;
  25. };
  26. export default function InvoiceRoute() {
  27. const invoice = useLoaderData<Invoice>();
  28. return <InvoiceView invoice={invoice} />;
  29. }
  30. export function CatchBoundary() {
  31. // this returns { status, statusText, data }
  32. const caught = useCatch<ThrownResponses>();
  33. switch (caught.status) {
  34. case 401:
  35. return (
  36. <div>
  37. <p>You don't have access to this invoice.</p>
  38. <p>
  39. Contact {invoiceCatch.data.invoiceOwnerEmail} to
  40. get access
  41. </p>
  42. </div>
  43. );
  44. case 404:
  45. return <div>Invoice not found!</div>;
  46. }
  47. // You could also `throw new Error("Unknown status in catch boundary")`.
  48. // This will be caught by the closest `ErrorBoundary`.
  49. return (
  50. <div>
  51. Something went wrong: {invoiceCatch.status}{" "}
  52. {invoiceCatch.statusText}
  53. </div>
  54. );
  55. }

action

Like loader, action is a server only function to handle data mutations and other actions. If a non-GET request is made to your route (POST, PUT, PATCH, DELETE) then the action is called before the loaders.

Actions have the same API as loaders, the only difference is when they are called.

This enables you to co-locate everything about a data set in a single route module: the data read, the component that renders the data, and the data writes:

  1. import { redirect, Form } from "remix";
  2. import { fakeGetTodos, fakeCreateTodo } from "~/utils/db";
  3. import { TodoList } from "~/components/TodoList";
  4. export async function loader() {
  5. return fakeGetTodos();
  6. }
  7. export async function action({ request }) {
  8. const body = await request.formData();
  9. const todo = await fakeCreateTodo({
  10. title: body.get("title")
  11. });
  12. return redirect(`/todos/${todo.id}`);
  13. }
  14. export default function Todos() {
  15. const data = useLoaderData();
  16. return (
  17. <div>
  18. <TodoList todos={data} />
  19. <Form method="post">
  20. <input type="text" name="title" />
  21. <button type="submit">Create Todo</button>
  22. </Form>
  23. </div>
  24. );
  25. }

When a POST is made to a URL, multiple routes in your route hierarchy will match the URL. Unlike a GET to loaders, where all of them are called to build the UI, only one action is called.

The route called will be the deepest matching route, unless the deepest matching route is an “index route”. In this case, it will post to the parent route of the index (because they share the same URL, the parent wins).

If you want to post to an index route use ?index in the action: <Form action="/accounts?index" method="post" />

action urlroute action
/accounts?indexroutes/accounts/index.js
/accountsroutes/accounts.js

Also note that forms without an action prop (<Form method="post">) will automatically post to the same route within which they are rendered, so using the ?index param to disambiguate between parent and index routes is only useful if you’re posting to an index route from somewhere besides the index route itself. If you’re posting from the index route to itself, or from the parent route to itself, you don’t need to define a <Form action> at all, just omit it: <Form method="post">.

See also:

headers

Each route can define it’s own HTTP headers. One of the common headers is the Cache-Control header that indicates to browser and CDN caches where and for how long a page is able to be cached.

  1. export function headers({ loaderHeaders, parentHeaders }) {
  2. return {
  3. "X-Stretchy-Pants": "its for fun",
  4. "Cache-Control": "max-age=300, s-maxage=3600"
  5. };
  6. }

Usually your data is a better indicator of your cache duration than your route module (data tends to be more dynamic than markup), so the loader’s headers are passed in to headers() too:

  1. export function headers({ loaderHeaders }) {
  2. return {
  3. "Cache-Control": loaderHeaders.get("Cache-Control")
  4. };
  5. }

Note: loaderHeaders is an instance of the Web Fetch API Headers class.

Because Remix has nested routes, there’s a battle of the headers to be won when nested routes match. In this case, the deepest route wins. Consider these files in the routes directory:

  1. ├── users.tsx
  2. └── users
  3. ├── $userId.tsx
  4. └── $userId
  5. └── profile.tsx

If we are looking at /users/123/profile then three routes are rendering:

  1. <Users>
  2. <UserId>
  3. <Profile />
  4. </UserId>
  5. </Users>

If all three define headers, the deepest module wins, in this case profile.tsx.

We don’t want surprise headers in your responses, so it’s your job to merge them if you’d like. Remix passes in the parentHeaders to your headers function. So users.tsx headers get passed to $userId.tsx, and then $userId.tsx headers are passed to profile.tsx headers.

That is all to say that Remix has given you a very large gun with which to shoot your foot. You need to be careful not to send a Cache-Control from a child route module that is more aggressive than a parent route. Here’s some code that picks the least aggressive caching in these cases:

  1. import parseCacheControl from "parse-cache-control";
  2. export function headers({ loaderHeaders, parentHeaders }) {
  3. const loaderCache = parseCacheControl(
  4. loaderHeaders.get("Cache-Control")
  5. );
  6. const parentCache = parseCacheControl(
  7. parentHeaders.get("Cache-Control")
  8. );
  9. // take the most conservative between the parent and loader, otherwise
  10. // we'll be too aggressive for one of them.
  11. const maxAge = Math.min(
  12. loaderCache["max-age"],
  13. parentCache["max-age"]
  14. );
  15. return {
  16. "Cache-Control": `max-age=${maxAge}`
  17. };
  18. }

All that said, you can avoid this entire problem by not defining headers in parent routes and only in leaf routes. Every layout that can be visited directly will likely have an “index route”. If you only define headers on your leaf routes, not your parent routes, you will never have to worry about merging headers.

meta

The meta export will set meta tags for your html document. We highly recommend setting the title and description on every route besides layout routes (their index route will set the meta).

  1. import type { MetaFunction } from "remix";
  2. export const meta: MetaFunction = () => {
  3. return {
  4. title: "Something cool",
  5. description:
  6. "This becomes the nice preview on search results."
  7. };
  8. };

There are a few special cases like title renders a <title> tag, og:style tags will render <meta property content>, the rest render <meta name={key} content={value}/>.

In the case of nested routes, the meta tags are merged automatically, so parent routes can add meta tags without the child routes needing to copy them.

The links function defines which <link> elements to add to the page when the user visits a route.

  1. import type { LinksFunction } from "remix";
  2. export const links: LinksFunction = () => {
  3. return [
  4. {
  5. rel: "icon",
  6. href: "/favicon.png",
  7. type: "image/png"
  8. },
  9. {
  10. rel: "stylesheet",
  11. href: "https://example.com/some/styles.css"
  12. },
  13. { page: "/users/123" },
  14. {
  15. rel: "preload",
  16. href: "/images/banner.jpg",
  17. as: "image"
  18. }
  19. ];
  20. };

There are two types of link descriptors you can return:

HtmlLinkDescriptor

This is an object representation of a normal <link {...props} /> element. [View the MDN docs for the link API][link-tag].

The links export from a route should return an array of HtmlLinkDescriptor objects.

Examples:

  1. import type { LinksFunction } from "remix";
  2. import stylesHref from "../styles/something.css";
  3. export const links: LinksFunction = () => {
  4. return [
  5. // add a favicon
  6. {
  7. rel: "icon",
  8. href: "/favicon.png",
  9. type: "image/png"
  10. },
  11. // add an external stylesheet
  12. {
  13. rel: "stylesheet",
  14. href: "https://example.com/some/styles.css",
  15. crossOrigin: "true"
  16. },
  17. // add a local stylesheet, remix will fingerprint the file name for
  18. // production caching
  19. { rel: "stylesheet", href: stylesHref },
  20. // prefetch an image into the browser cache that the user is likely to see
  21. // as they interact with this page, perhaps they click a button to reveal in
  22. // a summary/details element
  23. {
  24. rel: "prefetch",
  25. as: "image",
  26. href: "/img/bunny.jpg"
  27. },
  28. // only prefetch it if they're on a bigger screen
  29. {
  30. rel: "prefetch",
  31. as: "image",
  32. href: "/img/bunny.jpg",
  33. media: "(min-width: 1000px)"
  34. }
  35. ];
  36. };

HtmlMetaDescriptor

This is an object representation and abstraction of a <meta {...props} /> element and its attributes. View the MDN docs for the meta API.

The meta export from a route should return a single HtmlMetaDescriptor object.

Almost every meta element takes a name and content attribute, with the exception of OpenGraph tags which use property instead of name. In either case, the attributes represent a key/value pair for each tag. Each pair in the HtmlMetaDescriptor object represents a separate meta element, and Remix maps each to the correct attributes for that tag.

The meta object can also hold a title reference which maps to the HTML element</a></p> <p>Examples:</p> <pre><code>import type { MetaFunction } from "remix"; export const meta: MetaFunction = () => { return { title: "Josie's Shake Shack", // <title>Josie's Shake Shack</title> description: "Delicious shakes", // <meta name="description" content="Delicious shakes"> "og:image": "https://josiesshakeshack.com/logo.jpg" // <meta property="og:image" content="https://josiesshakeshack.com/logo.jpg"> }; }; </code></pre><h4 id="h4--code-pagelinkdescriptor-code-"><a name="<code>PageLinkDescriptor</code>" class="reference-link"></a><code>PageLinkDescriptor</code></h4><p>These descriptors allow you to prefetch the resources for a page the user is likely to navigate to. While this API is useful, you might get more mileage out of <code><Link prefetch="render"></code> instead. But if you’d like, you can get the same behavior with this API.</p> <pre><code>export function links() { return [{ page: "/posts/public" }]; } </code></pre><p>This loads up the JavaScript modules, loader data, and the stylesheets (defined in the <code>links</code> exports of the next routes) into the browser cache before the user even navigates there.</p> <p>Be careful with this feature. You don’t want to download 10MB of JavaScript and data for pages the user probably won’t ever visit.</p> <h3 id="h3-catchboundary"><a name="CatchBoundary" class="reference-link"></a>CatchBoundary</h3><p>A <code>CatchBoundary</code> is a React component that renders whenever an action or loader throws a <code>Response</code>.</p> <p><strong>Note:</strong> We use the word “catch” to represent the codepath taken when a <code>Response</code> type is thrown; you thought about bailing from the “happy path”. This is different from an uncaught error you did not expect to occur.</p> <p>A Remix <code>CatchBoundary</code> component works just like a route component, but instead of <code>useLoaderData</code> you have access to <code>useCatch</code>. When a response is thrown in an action or loader, the <code>CatchBoundary</code> will be rendered in it’s place, nested inside parent routes.</p> <p>A <code>CatchBoundary</code> component has access to the status code and thrown response data through <code>useCatch</code>.</p> <pre><code>import { useCatch } from "remix"; export function CatchBoundary() { const caught = useCatch(); return ( <div> <h1>Caught</h1> <p>Status: {caught.status}</p> <pre> <code>{JSON.stringify(caught.data, null, 2)}</code> </pre> </div> ); } </code></pre><h3 id="h3-errorboundary"><a name="ErrorBoundary" class="reference-link"></a>ErrorBoundary</h3><p>An <code>ErrorBoundary</code> is a React component that renders whenever there is an error anywhere on the route, either during rendering or during data loading.</p> <p><strong>Note:</strong> We use the word “error” to mean an uncaught exception; something you didn’t anticipate happening. This is different from other types of “errors” that you are able to recover from easily, for example a 404 error where you can still show something in the user interface to indicate you weren’t able to find some data.</p> <p>A Remix <code>ErrorBoundary</code> component works just like normal React <a href="https://reactjs.org/docs/error-boundaries.html">error boundaries</a>, but with a few extra capabilities. When there is an error in your route component, the <code>ErrorBoundary</code> will be rendered in its place, nested inside any parent routes. <code>ErrorBoundary</code> components also render when there is an error in the <code>loader</code> or <code>action</code> functions for a route, so all errors for that route may be handled in one spot.</p> <p>An <code>ErrorBoundary</code> component receives one prop: the <code>error</code> that occurred.</p> <pre><code>export function ErrorBoundary({ error }) { return ( <div> <h1>Error</h1> <p>{error.message}</p> <p>The stack trace is:</p> <pre>{error.stack}</pre> </div> ); } </code></pre><h3 id="h3-handle"><a name="handle" class="reference-link"></a>handle</h3><p>Exporting a handle allows you to create application conventions with the <code>useMatches()</code> hook. You can put whatever values you want on it:</p> <pre><code>export const handle = { its: "all yours" }; </code></pre><p>This is almost always used on conjunction with <code>useMatches</code>. To see what kinds of things you can do with it, refer to <a href="https://remix.run/docs/en/v1.0.6/remix/#usematches">useMatches</a> for more information.</p> <h3 id="h3-unstable_shouldreload"><a name="unstable_shouldReload" class="reference-link"></a>unstable_shouldReload</h3><p>This API is unstable, we’re confident in the use cases it solves but aren’t sure about the API yet, it may change in the future.</p> <p>This feature is an <em>additional</em> optimization. In general, Remix’s design does a great job of only calling the loaders that the next page needs and ensuring your UI is in sync with your server. When you use this feature you risk your UI getting out of sync with your server. Use with caution!</p> <p>This function lets apps optimize which routes should be reloaded on some client-side transitions.</p> <pre><code>import type { ShouldReloadFunction } from "remix"; export const unstable_shouldReload: ShouldReloadFunction = ({ // same params that go to `loader` and `action` params, // a possible form submission that caused this to be reloaded submission, // the next URL being used to render this page url, // the previous URL used to render this page prevUrl }) => false; // or `true`; </code></pre><p>During client-side transitions, Remix will optimize reloading of routes that are already rendering, like not reloading layout routes that aren’t changing. In other cases, like form submissions or search param changes, Remix doesn’t know which routes need to be reloaded so it reloads them all to be safe. This ensures data mutations from the submission or changes in the search params are reflected across the entire page.</p> <p>This function lets apps further optimize by returning <code>false</code> when Remix is about to reload a route. There are three cases when Remix will reload a route and you have the opportunity to optimize:</p> <ul> <li>if the <code>url.search</code> changes (while the <code>url.pathname</code> is the same)</li><li>after actions are called</li><li>“refresh” link clicks (click link to same URL)</li></ul> <p>Otherwise Remix will reload the route and you have no choice:</p> <ul> <li>A route matches the new URL that didn’t match before</li><li>The <code>url.pathname</code> changed (including route params)</li></ul> <p>Here are a couple of common use-cases:</p> <h4 id="h4-never-reloading-the-root"><a name="Never reloading the root" class="reference-link"></a>Never reloading the root</h4><p>It’s common for root loaders to return data that never changes, like environment variables to be sent to the client app. In these cases you never need the root loader to be called again. For this case, you can simply <code>return false</code>.</p> <pre><code>export const loader = () => { return { ENV: { CLOUDINARY_ACCT: process.env.CLOUDINARY_ACCT, STRIPE_PUBLIC_KEY: process.env.STRIPE_PUBLIC_KEY } }; }; export const unstable_shouldReload = () => false; </code></pre><p>With this in place, Remix will no longer make a request to your root loader for any reason, not after form submissions, not after search param changes, etc.</p> <h4 id="h4-ignoring-search-params"><a name="Ignoring search params" class="reference-link"></a>Ignoring search params</h4><p>Another common case is when you’ve got nested routes and a child component has a feature that uses the search params in the URL, like a search page or some tabs with state you want to keep in the search params.</p> <p>Consider these routes:</p> <pre><code>└── $projectId.tsx └── activity.tsx </code></pre><p>And lets say the UI looks something like this:</p> <pre><code>┌──────────────────────────────┐ │ Project: Design Revamp │ ├────────┬─────────┬───────────┤ │ Tasks │ Collabs │ >ACTIVITY │ ├────────┴─────────┴───────────┤ │ Search: _____________ │ │ │ │ - Ryan added an image │ │ │ │ - Michael commented │ │ │ └──────────────────────────────┘ </code></pre><p>The <code>$activity.tsx</code> loader can use the search params to filter the list, so visiting a URL like <code>/projects/design-revamp/activity?search=image</code> could filter the list of results. Maybe it looks something like this:</p> <pre><code>export function loader({ request, params }) { const url = new URL(request.url); return exampleDb.activity.findAll({ where: { projectId: params.projectId, name: { contains: url.searchParams.get("search") } } }); } </code></pre><p>This is great for the activity route, but Remix doesn’t know if the parent loader, <code>$projectId.tsx</code> <em>also</em> cares about the search params. That’s why Remix does the safest thing and reloads all the routes on the page when the search params change.</p> <p>In this UI, that’s wasted bandwidth for the user, your server, and your database because <code>$projectId.tsx</code> doesn’t use the search params. Consider that our loader for <code>$projectId.tsx</code> looks something like this:</p> <pre><code>export function loader({ params }) { return fakedb.findProject(params.projectId); } </code></pre><p>We want this loader to be called only if the project has had an update, so we can make this really simple and just say to reload if there is a non-GET submission:</p> <pre><code>export function unstable_shouldReload({ submission }) { return submission && submission.method !== "GET"; } </code></pre><p>Now if the child route causes the search params to change, this route will no longer be reloaded because there was no submission.</p> <p>When you want to optimize a loader, instead of thinking about the thing causing the reload (search params), think only about the loader’s requirements that you’re optimizing.</p> <p>You may want to get more granular and reload only for submissions to this project:</p> <pre><code>export function unstable_shouldReload({ params, submission }) { return ( submission && submission.action === `/projects/${params.projectId}` ); } </code></pre><p>You need to be very careful here, though. That project (or its nested relationships) may be updated by other actions and your app will get out of sync if you don’t also consider them.</p> <h2 id="h2-asset-url-imports"><a name="Asset URL Imports" class="reference-link"></a>Asset URL Imports</h2><p>Any files inside the <code>app</code> folder can be imported into your modules. Remix will:</p> <ol> <li>Copy the file to your browser build directory</li><li>Fingerprint the file for long-term caching</li><li>Return the public URL to your module to be used while rendering</li></ol> <p>It’s most common for stylesheets, but can used for anything.</p> <pre><code>// root.tsx import type { LinksFunction } from "remix"; import styles from "./styles/app.css"; import banner from "./images/banner.jpg"; export const links: LinksFunction = () => { return [{ rel: "stylesheet", href: styles }]; }; export default function Page() { return ( <div> <h1>Some Page</h1> <img src={banner} /> </div> ); } </code></pre><!-- 原文:https://remix.run/docs/en/v1/api/conventions -->