Home

Awesome

preact-iso

Preact Slack Community

Isomorphic async tools for Preact.

Routing

preact-iso offers a simple router for Preact with conventional and hooks-based APIs. The <Router> component is async-aware: when transitioning from one route to another, if the incoming route suspends (throws a Promise), the outgoing route is preserved until the new one becomes ready.

import { lazy, LocationProvider, ErrorBoundary, Router, Route } from 'preact-iso';

// Synchronous
import Home from './routes/home.js';

// Asynchronous (throws a promise)
const Profiles = lazy(() => import('./routes/profiles.js'));
const Profile = lazy(() => import('./routes/profile.js'));
const NotFound = lazy(() => import('./routes/_404.js'));

const App = () => (
	<LocationProvider>
		<ErrorBoundary>
			<Router>
				<Home path="/" />
				{/* Alternative dedicated route component for better TS support */}
				<Route path="/profiles" component={Profiles} />
				<Route path="/profiles/:id" component={Profile} />
				{/* `default` prop indicates a fallback route. Useful for 404 pages */}
				<NotFound default />
			</Router>
		</ErrorBoundary>
	</LocationProvider>
);

Progressive Hydration: When the app is hydrated on the client, the route (Home or Profile in this case) suspends. This causes hydration for that part of the page to be deferred until the route's import() is resolved, at which point that part of the page automatically finishes hydrating.

Seamless Routing: Switch switching between routes on the client, the Router is aware of asynchronous dependencies in routes. Instead of clearing the current route and showing a loading spinner while waiting for the next route (or its data), the router preserves the current route in-place until the incoming route has finished loading, then they are swapped.

Nested Routing: Nested routes are supported by using multiple Router components. Partially matched routes end with a wildcard /* and the remaining value will be past to continue matching with if there are any further routes.

Prerendering

prerender() renders a Virtual DOM tree to an HTML string using preact-render-to-string. The Promise returned from prerender() resolves to an Object with html and links[] properties. The html property contains your pre-rendered static HTML markup, and links is an Array of any non-external URL strings found in links on the generated page.

Primarily meant for use with prerendering via @preact/preset-vite or other prerendering systems that share the API. If you're server-side rendering your app via any other method, you can use preact-render-to-string (specifically renderToStringAsync()) directly.

import { LocationProvider, ErrorBoundary, Router, lazy, prerender as ssr } from 'preact-iso';

// Asynchronous (throws a promise)
const Foo = lazy(() => import('./foo.js'));

const App = () => (
	<LocationProvider>
		<ErrorBoundary>
			<Router>
				<Foo path="/" />
			</Router>
		</ErrorBoundary>
	</LocationProvider>
);

hydrate(<App />);

export async function prerender(data) {
	return await ssr(<App />);
}

API Docs

LocationProvider

A context provider that provides the current location to its children. This is required for the router to function.

Typically, you would wrap your entire app in this provider:

import { LocationProvider } from 'preact-iso';

const App = () => (
    <LocationProvider>
        {/* Your app here */}
    </LocationProvider>
);

Router

Props:

import { LocationProvider, Router } from 'preact-iso';

const App = () => (
	<LocationProvider>
		<Router
			onRouteChange={(url) => console.log('Route changed to', url)}
			onLoadStart={(url) => console.log('Starting to load', url)}
			onLoadEnd={(url) => console.log('Finished loading', url)}
		>
			<Home path="/" />
			<Profile path="/profile" />
		</Router>
	</LocationProvider>
);

Route

There are two ways to define routes using preact-iso:

  1. Append router params to the route components directly: <Home path="/" />
  2. Use the Route component instead: <Route path="/" component={Home} />

Appending arbitrary props to components not unreasonable in JavaScript, as JS is a dynamic language that's perfectly happy to support dynamic & arbitrary interfaces. However, TypeScript, which many of us use even when writing JS (via TS's language server), is not exactly a fan of this sort of interface design.

TS does not (yet) allow for overriding a child's props from the parent component so we cannot, for instance, define <Home> as taking no props unless it's a child of a <Router>, in which case it can have a path prop. This leaves us with a bit of a dilemma: either we define all of our routes as taking path props so we don't see TS errors when writing <Home path="/" /> or we create wrapper components to handle the route definitions.

While <Home path="/" /> is completely equivalent to <Route path="/" component={Home} />, TS users may find the latter preferable.

import { LocationProvider, Router, Route } from 'preact-iso';

const App = () => (
	<LocationProvider>
		<Router>
			{/* Both of these are equivalent */}
			<Home path="/" />
			<Route path="/" component={Home} />

			<Profile path="/profile" />
			<NotFound default />
		</Router>
	</LocationProvider>
);

Props for any route component:

Specific to the Route component:

Path Segment Matching

Paths are matched using a simple string matching algorithm. The following features may be used:

These can then be composed to create more complex routes:

useLocation

A hook to work with the LocationProvider to access location context.

Returns an object with the following properties:

useRoute

A hook to access current route information. Unlike useLocation, this hook only works within <Router> components.

Returns an object with the following properties:

lazy

Make a lazily-loaded version of a Component.

lazy() takes an async function that resolves to a Component, and returns a wrapper version of that Component. The wrapper component can be rendered right away, even though the component is only loaded the first time it is rendered.

import { lazy, LocationProvider, Router } from 'preact-iso';

// Synchronous, not code-splitted:
// import Home from './routes/home.js';
// import Profile from './routes/profile.js';

// Asynchronous, code-splitted:
const Home = lazy(() => import('./routes/home.js'));
const Profile = lazy(() => import('./routes/profile.js'));

const App = () => (
	<LocationProvider>
		<Router>
			<Home path="/" />
			<Profile path="/profile" />
		</Router>
	</LocationProvider>
);

ErrorBoundary

A simple component to catch errors in the component tree below it.

Props:

import { LocationProvider, ErrorBoundary, Router } from 'preact-iso';

const App = () => (
	<LocationProvider>
		<ErrorBoundary onError={(e) => console.log(e)}>
			<Router>
				<Home path="/" />
				<Profile path="/profile" />
			</Router>
		</ErrorBoundary>
	</LocationProvider>
);

hydrate

A thin wrapper around Preact's hydrate export, it switches between hydrating and rendering the provided element, depending on whether the current page has been prerendered. Additionally, it checks to ensure it's running in a browser context before attempting any rendering, making it a no-op during SSR.

Pairs with the prerender() function.

Params:

import { hydrate } from 'preact-iso';

const App = () => (
	<div class="app">
		<h1>Hello World</h1>
	</div>
);

hydrate(<App />);

However, it is just a simple utility method. By no means is it essential to use, you can always use Preact's hydrate export directly.

prerender

Renders a Virtual DOM tree to an HTML string using preact-render-to-string. The Promise returned from prerender() resolves to an Object with html and links[] properties. The html property contains your pre-rendered static HTML markup, and links is an Array of any non-external URL strings found in links on the generated page.

Pairs primarily with @preact/preset-vite's prerendering.

Params:

import { LocationProvider, ErrorBoundary, Router, lazy, prerender } from 'preact-iso';

// Asynchronous (throws a promise)
const Foo = lazy(() => import('./foo.js'));
const Bar = lazy(() => import('./bar.js'));

const App = () => (
	<LocationProvider>
		<ErrorBoundary>
			<Router>
				<Foo path="/" />
				<Bar path="/bar" />
			</Router>
		</ErrorBoundary>
	</LocationProvider>
);

const { html, links } = await prerender(<App />);

License

MIT