Remix Utils - v9.3.1
    Preparing search index...

    Module Hook/Use Should Hydrate

    Note

    Install using bunx shadcn@latest add @remix-utils/use-should-hydrate.

    Note

    This depends on react-router and react.

    If you are building a Remix application where most routes are static, and you want to avoid loading client-side JS, you can use this hook, plus some conventions, to detect if one or more active routes needs JS and only render the Scripts component in that case.

    In your document component, you can call this hook to dynamically render the Scripts component if needed.

    import type { ReactNode } from "react";
    import { Links, LiveReload, Meta, Scripts } from "react-router";
    import { useShouldHydrate } from "remix-utils/use-should-hydrate";

    interface DocumentProps {
    children: ReactNode;
    title?: string;
    }

    export function Document({ children, title }: DocumentProps) {
    let shouldHydrate = useShouldHydrate();
    return (
    <html lang="en">
    <head>
    <meta charSet="utf-8" />
    <link rel="icon" href="/favicon.png" type="image/png" />
    {title ? <title>{title}</title> : null}
    <Meta />
    <Links />
    </head>
    <body>
    {children}
    {shouldHydrate && <Scripts />}
    <LiveReload />
    </body>
    </html>
    );
    }

    Now, you can export a handle object with the hydrate property as true in any route module.

    export let handle = { hydrate: true };
    

    This will mark the route as requiring JS hydration.

    In some cases, a route may need JS based on the data the loader returned. For example, if you have a component to purchase a product, but only authenticated users can see it, you don't need JS until the user is authenticated. In that case, you can make hydrate be a function receiving your loader data.

    export let handle = {
    hydrate(data: LoaderData) {
    return data.user.isAuthenticated;
    },
    };

    The useShouldHydrate hook will detect hydrate as a function and call it using the route data.

    Functions

    useShouldHydrate