├── .gitignore
├── public
└── favicon.ico
├── vite.config.ts
├── app
├── routes
│ ├── _index.tsx
│ └── defer.$id.tsx
├── entry.client.tsx
├── root.tsx
└── entry.server.tsx
├── README.md
├── tsconfig.json
├── package.json
└── .eslintrc.cjs
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
2 |
3 | /.cache
4 | /build
5 | .env
6 |
--------------------------------------------------------------------------------
/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kiliman/remix-suspense/HEAD/public/favicon.ico
--------------------------------------------------------------------------------
/vite.config.ts:
--------------------------------------------------------------------------------
1 | import { vitePlugin as remix } from "@remix-run/dev";
2 | import { installGlobals } from "@remix-run/node";
3 | import { defineConfig } from "vite";
4 | import tsconfigPaths from "vite-tsconfig-paths";
5 |
6 | installGlobals();
7 |
8 | export default defineConfig({
9 | plugins: [remix(), tsconfigPaths()],
10 | });
11 |
--------------------------------------------------------------------------------
/app/routes/_index.tsx:
--------------------------------------------------------------------------------
1 | import type { MetaFunction } from "@remix-run/node";
2 | import { Link } from "@remix-run/react";
3 |
4 | export const meta: MetaFunction = () => {
5 | return [
6 | { title: "New Remix App" },
7 | { name: "description", content: "Welcome to Remix!" },
8 | ];
9 | };
10 |
11 | export default function Index() {
12 | return (
13 |
14 |
Welcome to Remix
15 |
16 | -
17 | Defer 123
18 |
19 |
20 |
21 | );
22 | }
23 |
--------------------------------------------------------------------------------
/app/entry.client.tsx:
--------------------------------------------------------------------------------
1 | /**
2 | * By default, Remix will handle hydrating your app on the client for you.
3 | * You are free to delete this file if you'd like to, but if you ever want it revealed again, you can run `npx remix reveal` ✨
4 | * For more information, see https://remix.run/file-conventions/entry.client
5 | */
6 |
7 | import { RemixBrowser } from "@remix-run/react";
8 | import { startTransition, StrictMode } from "react";
9 | import { hydrateRoot } from "react-dom/client";
10 |
11 | startTransition(() => {
12 | hydrateRoot(
13 | document,
14 |
15 |
16 |
17 | );
18 | });
19 |
--------------------------------------------------------------------------------
/app/root.tsx:
--------------------------------------------------------------------------------
1 | import {
2 | Links,
3 | Meta,
4 | Outlet,
5 | Scripts,
6 | ScrollRestoration,
7 | } from "@remix-run/react";
8 |
9 | export function Layout({ children }: { children: React.ReactNode }) {
10 | return (
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 | {children}
20 |
21 |
22 |
23 |
24 | );
25 | }
26 |
27 | export default function App() {
28 | return ;
29 | }
30 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Remix Suspense
2 |
3 | This example shows how to use `` to ensure
4 | that the fallback component is displayed when navigating to the same route
5 | component but with different URL. For example `/defer/123` => `/defer/456`
6 |
7 | If you're rendering the same route but with different data, Remix does not
8 | unmount your component before rendering. Just like in regular React, it's
9 | fetching the data and updating context and React is responsible for rendering.
10 |
11 | To ensure the Suspense boundary is unmounted on route change, I recommend
12 | setting a key equal to the current path.
13 |
14 | ```ts
15 | const location = useLocation()
16 | return ...
17 | ```
18 |
19 | ⚡️ StackBlitz https://stackblitz.com/github/kiliman/remix-suspense
20 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "include": [
3 | "**/*.ts",
4 | "**/*.tsx",
5 | "**/.server/**/*.ts",
6 | "**/.server/**/*.tsx",
7 | "**/.client/**/*.ts",
8 | "**/.client/**/*.tsx"
9 | ],
10 | "compilerOptions": {
11 | "lib": ["DOM", "DOM.Iterable", "ES2022"],
12 | "types": ["@remix-run/node", "vite/client"],
13 | "isolatedModules": true,
14 | "esModuleInterop": true,
15 | "jsx": "react-jsx",
16 | "module": "ESNext",
17 | "moduleResolution": "Bundler",
18 | "resolveJsonModule": true,
19 | "target": "ES2022",
20 | "strict": true,
21 | "allowJs": true,
22 | "skipLibCheck": true,
23 | "forceConsistentCasingInFileNames": true,
24 | "baseUrl": ".",
25 | "paths": {
26 | "~/*": ["./app/*"]
27 | },
28 |
29 | // Vite takes care of building everything, not tsc.
30 | "noEmit": true
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/app/routes/defer.$id.tsx:
--------------------------------------------------------------------------------
1 | import { type LoaderFunctionArgs, defer } from "@remix-run/node";
2 | import {
3 | Await,
4 | useLoaderData,
5 | useLocation,
6 | useNavigate,
7 | useParams,
8 | } from "@remix-run/react";
9 | import { Suspense } from "react";
10 |
11 | export async function loader({ params }: LoaderFunctionArgs) {
12 | return defer({
13 | data: new Promise((resolve) => setTimeout(resolve, 2000)).then(() => {
14 | return { message: `This is slow data for id ${params.id}` };
15 | }),
16 | });
17 | }
18 |
19 | export default function Component() {
20 | const { data } = useLoaderData();
21 | const { id } = useParams();
22 | const location = useLocation();
23 | const navigate = useNavigate();
24 |
25 | return (
26 |
27 |
28 |
36 |
37 |
38 | Error loading slow data!}>
39 | {(data) => {JSON.stringify(data, null, 2)}}
40 |
41 |
42 |
43 | );
44 | }
45 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "remix-suspense",
3 | "private": true,
4 | "sideEffects": false,
5 | "type": "module",
6 | "scripts": {
7 | "build": "remix vite:build",
8 | "dev": "remix vite:dev",
9 | "lint": "eslint --ignore-path .gitignore --cache --cache-location ./node_modules/.cache/eslint .",
10 | "start": "remix-serve ./build/server/index.js",
11 | "typecheck": "tsc"
12 | },
13 | "dependencies": {
14 | "@remix-run/node": "^2.8.1",
15 | "@remix-run/react": "^2.8.1",
16 | "@remix-run/serve": "^2.8.1",
17 | "isbot": "^4.1.0",
18 | "react": "^18.3.0-canary-a870b2d54-20240314",
19 | "react-dom": "^18.3.0-canary-a870b2d54-20240314"
20 | },
21 | "devDependencies": {
22 | "@remix-run/dev": "^2.8.1",
23 | "@types/react": "^18.2.20",
24 | "@types/react-dom": "^18.2.7",
25 | "@typescript-eslint/eslint-plugin": "^6.7.4",
26 | "@typescript-eslint/parser": "^6.7.4",
27 | "eslint": "^8.38.0",
28 | "eslint-import-resolver-typescript": "^3.6.1",
29 | "eslint-plugin-import": "^2.28.1",
30 | "eslint-plugin-jsx-a11y": "^6.7.1",
31 | "eslint-plugin-react": "^7.33.2",
32 | "eslint-plugin-react-hooks": "^4.6.0",
33 | "typescript": "^5.1.6",
34 | "vite": "^5.1.0",
35 | "vite-tsconfig-paths": "^4.2.1"
36 | },
37 | "overrides": {
38 | "react": "^18.3.0-canary-a870b2d54-20240314",
39 | "react-dom": "^18.3.0-canary-a870b2d54-20240314"
40 | },
41 | "engines": {
42 | "node": ">=18.0.0"
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/.eslintrc.cjs:
--------------------------------------------------------------------------------
1 | /**
2 | * This is intended to be a basic starting point for linting in your app.
3 | * It relies on recommended configs out of the box for simplicity, but you can
4 | * and should modify this configuration to best suit your team's needs.
5 | */
6 |
7 | /** @type {import('eslint').Linter.Config} */
8 | module.exports = {
9 | root: true,
10 | parserOptions: {
11 | ecmaVersion: "latest",
12 | sourceType: "module",
13 | ecmaFeatures: {
14 | jsx: true,
15 | },
16 | },
17 | env: {
18 | browser: true,
19 | commonjs: true,
20 | es6: true,
21 | },
22 |
23 | // Base config
24 | extends: ["eslint:recommended"],
25 |
26 | overrides: [
27 | // React
28 | {
29 | files: ["**/*.{js,jsx,ts,tsx}"],
30 | plugins: ["react", "jsx-a11y"],
31 | extends: [
32 | "plugin:react/recommended",
33 | "plugin:react/jsx-runtime",
34 | "plugin:react-hooks/recommended",
35 | "plugin:jsx-a11y/recommended",
36 | ],
37 | settings: {
38 | react: {
39 | version: "detect",
40 | },
41 | formComponents: ["Form"],
42 | linkComponents: [
43 | { name: "Link", linkAttribute: "to" },
44 | { name: "NavLink", linkAttribute: "to" },
45 | ],
46 | "import/resolver": {
47 | typescript: {},
48 | },
49 | },
50 | },
51 |
52 | // Typescript
53 | {
54 | files: ["**/*.{ts,tsx}"],
55 | plugins: ["@typescript-eslint", "import"],
56 | parser: "@typescript-eslint/parser",
57 | settings: {
58 | "import/internal-regex": "^~/",
59 | "import/resolver": {
60 | node: {
61 | extensions: [".ts", ".tsx"],
62 | },
63 | typescript: {
64 | alwaysTryTypes: true,
65 | },
66 | },
67 | },
68 | extends: [
69 | "plugin:@typescript-eslint/recommended",
70 | "plugin:import/recommended",
71 | "plugin:import/typescript",
72 | ],
73 | },
74 |
75 | // Node
76 | {
77 | files: [".eslintrc.cjs"],
78 | env: {
79 | node: true,
80 | },
81 | },
82 | ],
83 | };
84 |
--------------------------------------------------------------------------------
/app/entry.server.tsx:
--------------------------------------------------------------------------------
1 | /**
2 | * By default, Remix will handle generating the HTTP Response for you.
3 | * You are free to delete this file if you'd like to, but if you ever want it revealed again, you can run `npx remix reveal` ✨
4 | * For more information, see https://remix.run/file-conventions/entry.server
5 | */
6 |
7 | import { PassThrough } from "node:stream";
8 |
9 | import type { AppLoadContext, EntryContext } from "@remix-run/node";
10 | import { createReadableStreamFromReadable } from "@remix-run/node";
11 | import { RemixServer } from "@remix-run/react";
12 | import { isbot } from "isbot";
13 | import { renderToPipeableStream } from "react-dom/server";
14 |
15 | const ABORT_DELAY = 5_000;
16 |
17 | export default function handleRequest(
18 | request: Request,
19 | responseStatusCode: number,
20 | responseHeaders: Headers,
21 | remixContext: EntryContext,
22 | // This is ignored so we can keep it in the template for visibility. Feel
23 | // free to delete this parameter in your app if you're not using it!
24 | // eslint-disable-next-line @typescript-eslint/no-unused-vars
25 | loadContext: AppLoadContext
26 | ) {
27 | return isbot(request.headers.get("user-agent") || "")
28 | ? handleBotRequest(
29 | request,
30 | responseStatusCode,
31 | responseHeaders,
32 | remixContext
33 | )
34 | : handleBrowserRequest(
35 | request,
36 | responseStatusCode,
37 | responseHeaders,
38 | remixContext
39 | );
40 | }
41 |
42 | function handleBotRequest(
43 | request: Request,
44 | responseStatusCode: number,
45 | responseHeaders: Headers,
46 | remixContext: EntryContext
47 | ) {
48 | return new Promise((resolve, reject) => {
49 | let shellRendered = false;
50 | const { pipe, abort } = renderToPipeableStream(
51 | ,
56 | {
57 | onAllReady() {
58 | shellRendered = true;
59 | const body = new PassThrough();
60 | const stream = createReadableStreamFromReadable(body);
61 |
62 | responseHeaders.set("Content-Type", "text/html");
63 |
64 | resolve(
65 | new Response(stream, {
66 | headers: responseHeaders,
67 | status: responseStatusCode,
68 | })
69 | );
70 |
71 | pipe(body);
72 | },
73 | onShellError(error: unknown) {
74 | reject(error);
75 | },
76 | onError(error: unknown) {
77 | responseStatusCode = 500;
78 | // Log streaming rendering errors from inside the shell. Don't log
79 | // errors encountered during initial shell rendering since they'll
80 | // reject and get logged in handleDocumentRequest.
81 | if (shellRendered) {
82 | console.error(error);
83 | }
84 | },
85 | }
86 | );
87 |
88 | setTimeout(abort, ABORT_DELAY);
89 | });
90 | }
91 |
92 | function handleBrowserRequest(
93 | request: Request,
94 | responseStatusCode: number,
95 | responseHeaders: Headers,
96 | remixContext: EntryContext
97 | ) {
98 | return new Promise((resolve, reject) => {
99 | let shellRendered = false;
100 | const { pipe, abort } = renderToPipeableStream(
101 | ,
106 | {
107 | onShellReady() {
108 | shellRendered = true;
109 | const body = new PassThrough();
110 | const stream = createReadableStreamFromReadable(body);
111 |
112 | responseHeaders.set("Content-Type", "text/html");
113 |
114 | resolve(
115 | new Response(stream, {
116 | headers: responseHeaders,
117 | status: responseStatusCode,
118 | })
119 | );
120 |
121 | pipe(body);
122 | },
123 | onShellError(error: unknown) {
124 | reject(error);
125 | },
126 | onError(error: unknown) {
127 | responseStatusCode = 500;
128 | // Log streaming rendering errors from inside the shell. Don't log
129 | // errors encountered during initial shell rendering since they'll
130 | // reject and get logged in handleDocumentRequest.
131 | if (shellRendered) {
132 | console.error(error);
133 | }
134 | },
135 | }
136 | );
137 |
138 | setTimeout(abort, ABORT_DELAY);
139 | });
140 | }
141 |
--------------------------------------------------------------------------------