Bring React server‑side rendering to your frontend agnostic framework
Drih let's you pre‑build your React components and serve them as static files.
Drih also can turn them back into React components!
Features
Dehydrate
Dehydrate your React components into static files. Customize the source directory, the output directory and the file extension to your needs.
Request-time Inclusion
Include your dehydrated components at request time. Configure the hydration conditions as you see fit. Specify if you want to hydrate the component always, only when it's visible, on a specific viewport size, or both.
Hydrate
Hydrate your dehydrated components to turn them back into React components. A runtime that understands how the dehydrated components will get hydrated.
It reads your specified configuration and hydrates the components accordingly.
How does it work?
Asset pipeline
A Vite plugin that transforms your React components into static files, using ReactDOM server APIs. This keeps your components in sync as you develop them and when you bundle them.
Templating engine helpers
Helpers built for popular templating engines (Blade, Handlebars, etc.) that allow you to include your dehydrated components at request time and configure the hydration conditions as you see fit.
Hydration runtime
A client runtime that hydrates your dehydrated components back into React components, using ReactDOM client APIs. This allows you to re attach interactivity to your dehydrated components.
Example
This component was dehydrated and served as a static file.
But it got hydrated when it became visible in the viewport. Enjoy the zero FOUC!
Getting started
Prerequisites
- Node.js
- PNPM
- React
- React DOM
- Vite
Run pnpm add -D react react-dom vite
Install Drih
Run pnpm add -D @drih/dehydrate @drih/hydrate to install Drih as a development dependency.
Update your Vite configuration
Add the following to your vite.config.ts file:
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { hydratePlugin } from '@drih/hydrate/plugin';
import { dehydratePlugin } from '@drih/dehydrate/plugin';
export default defineConfig({
plugins: [
hydratePlugin(), // The order matters, hydratePlugin must be before dehydratePlugin.
dehydratePlugin(),
react(),
],
resolve: {
// This makes sure that only one copy of React and React DOM is used.
dedupe: ['react', 'react-dom'],
},
});
Add your Drih configuration
Add the following to a drih.config.js file:
import { defineConfig } from '@drih/dehydrate';
/**
* Define the configuration for the dehydrate plugin.
*/
export default defineConfig({
dehydrationSourceDir: 'resources/js/components', // Define our dehydration source directory.
dehydratedComponentsDir: 'resources/views/components/dehydrated', // Define our dehydrated components output directory.
dehydratedComponentFileExtension: '.blade.php', // Blade can include the Dehydrated Components as views.
dehydrationSourceFileExtension: '.tsx', // Supported formats are .tsx, .jsx
});
Setup your package.json scripts
If not already configured, add the following to your package.json file scripts:
"scripts": {
"build": "vite build",
"dehydrate": "drih-dehydrate",
"dev": "vite",
"test": "vitest run",
"typecheck": "tsc --noEmit"
}
Create your first component
This is a 'Hello World' example component. Create a HelloWorld.tsx file in the resources/js/components or your specified directory in 'dehydrationSourceDir' in your drih.config.js file:
'use client'; // This is required for components that need to be hydrated.
import { useEffect, useState } from 'react';
/**
* Greeting component used to exercise dehydration and hydration.
*
* @param {object} props Component props.
* @param {string} props.name Name shown in the greeting.
*
* @returns {React.JSX.Element} The greeting element.
*/
export default function HelloWorld({ name = 'Ada Lovelace' }: { name: string }): React.JSX.Element {
const [newName, setNewName] = useState(name);
useEffect(() => {
setNewName('John Doe');
}, []);
return <div>{`Hello ${newName}!`}</div>;
}
What happens if I ommit the 'use client' directive?
If you omit the 'use client' directive, the component will still be dehydrated into a static HTML string that you can still include in your view like any other static HTML string.
However, the 'use client' directive is required for components that need to be hydrated on the client side. When ommitted, the component won't be picked up by the hydration runtime and will remain static.
This is useful if you want to use the component in a static context, like a newsletter or email template, or you can use it to create all your UI in React while still using a server side rendering framework like Laravel or NestJS.
Start your Vite dev server
Run pnpm dev to start your Vite dev server. Or build your assets by running pnpm build. You should see the dehydrated 'Hello World' component generated in your configured dehydrated components directory.
Include your dehydrated component in your view
For this example we're using Drih's Blade plugin to include the dehydrated component in our view:
@hydrate('components.dehydrated.HelloWorld', $compoment_props, $hydration_options)
Install it by running composer require drih/blade.
Or include it manually
You don't need to install the Blade plugin to include the dehydrated component manually. You can manually create the wrapper element that the hydration runtime needs to find and hydrate:
<div data-drih-hydrate-component="HelloWorld" data-drih-hydrate-props="{}" data-drih-hydrate-when-its-intersecting data-drih-hydrate-when-its-media-matches="screen and (min-width: 768px)">
@include('components.dehydrated.HelloWorld')
</div>
The @include directive can be changed for any template engine way of including the dehydrated component.
The wrapper shell
The wrapper shell is the element hydrateComponents() finds in the document. The host calls that function with no arguments. The shell must have a data-drih-hydrate-component attribute that matches the component name, and optionally, a data-drih-hydrate-props attribute that matches the component props, a data-drih-hydrate-when-its-intersecting attribute and/or a data-drih-hydrate-when-its-media-matches attribute.
The data-drih-hydrate-props attribute is a JSON string that contains optional overrides for the component props default values. It is used to override the default component props by passing those values to the client side. If the data-drih-hydrate-props attribute is not present, the component will be hydrated with the default props.
The data-drih-hydrate-when-its-intersecting and data-drih-hydrate-when-its-media-matches attributes are optional and can be used to control when the component is hydrated. Our packages like Blade and Handlebars provide the mechanisms to help you create the wrapper shell elements in specific templating engines for you, but they are not strictly required.
Avoid the server vs client hydration mismatch pitfall
If the data-drih-hydrate-props attribute is present, the component will be hydrated with the values passed to the client side. If the data-drih-hydrate-props attribute values modify the compoment's first render tree, a hydration mismatch will occur.
Only use this attribute if you need to pass data from the server side to the client side in a context that doesn't modify the component's first render tree.
An example use case of this, is how we currently use the data-drih-hydrate-props attribute in this website to pass the session state to the client side and adjust what links our mobile navigation menu shows based on wether the user is logged in or not. Since the props we pass from the server to the client are not used until an interaction triggers opening the mobile navigation drawer, we don't need to worry about an hydration mismatch.
Use this attribute with caution make sure to validate a hydration mismatch doesn't occur by looking at the browser console logs for hydration mismatches. When used properly, this attribute will help you save on client-side API requests.
Include the hydration runtime
Add the following to your app.ts file:
import { hydrateComponents } from '@drih/hydrate';
// Handle the hydrate process for the components when the DOM is loaded.
// The components that are using the 'data-drih-hydrate-when-its-intersecting' and/or 'data-drih-hydrate-when-its-media-matches' attributes
// won't be hydrated until their configured conditions are met.
document.addEventListener('DOMContentLoaded', () => {
hydrateComponents();
});
Save the changes with your Vite dev pipeline running, or rebuild your assets by running pnpm build so the runtime is bundled in the served asset.
Load the page
Load the page in your browser and you should see the 'Hello World' component rendered. Enjoy using React SSR with Drih!
Special thanks
Special thanks to the following projects for being a source of inspiration and helping me learn:
- Laravel
- NestJS
- Astro
- The is-land package
- NextJS
- Vite
- React