Wouter

A minimalist-friendly ~1.5KB routing for React and Preact. Nothing else but...

README

Wouter — a super-tiny React router (logo by Katya Simacheva)
npm CI Coverage Coverage
wouter is a tiny router for modern React and Preact apps that relies on Hooks.
A router you wanted so bad in your project!

Features


by Katya Simacheva

- Zero dependency, only 1.36 KB gzipped vs 11KB
- Supports both React and Preact! Read
  _"Preact support" section_ for more details.
- No top-level `` component, it is **fully optional**.
- Mimics React Router's best practices by providing
  familiar [Route](#route-pathpattern-), [Link](#link-hrefpath-),
  [Switch](#switch-) and [Redirect](#redirect-topath-) components.
- Has hook-based API for more granular control over routing (like animations):
  [useLocation](#uselocation-hook-working-with-the-history),
  [useRoute](#useroute-the-power-of-hooks) and
  [useRouter](#userouter-accessing-the-router-object).

developers :sparkling_heart: wouter


... I love Wouter. It’s tiny, fully embraces hooks, and has an intuitive and barebones API. I can

accomplish everything I could with react-router with Wouter, and it just feels more minimalist

while not being inconvenient.

>

[Matt Miller, _An exhaustive React ecosystem for 2020_](https://medium.com/@mmiller42/an-exhaustive-react-guide-for-2020-7859f0bddc56)


Wouter provides a simple API that many developers and library authors appreciate. Some notable
projects that use wouter: arcade.design (React UI kit),
Ziro App and many more.

Table of Contents


- API
  - Hooks
    - [useRoute](#useroute-the-power-of-hooks)
    - [useLocation](#uselocation-hook-working-with-the-history)
    - [useRouter](#userouter-accessing-the-router-object)
- **[``](#route-pathpattern-)** - **[``](#link-hrefpath-)** - **[``](#switch-)** - **[``](#redirect-topath-)** - **[``](#router-hookhook-matchermatchfn-basebasepath-)**
      - [Using a path-to-regexp-based matcher](#using-a-path-to-regexp-based-matcher)
  - Base path

Getting Started


Check out this demo app below in order to get started:

  1. ``` js
  2. import { Link, Route } from "wouter";

  3. const App = () => (
  4.   <div>
  5.     <Link href="/users/1">
  6.       <a className="link">Profile</a>
  7.     </Link>
  8. <Route path="/about">About Us</Route>
  9.     <Route path="/users/:name">{(params) => <div>Hello, {params.name}!</div>}Route>
  10.     <Route path="/inbox" component={InboxPage} />
  11.   </div>
  12. );
  13. ```

Supporting IE11 and obsolete platforms


This library uses features like
and [const/let declarations](https://kangax.github.io/compat-table/es6/#test-const) and doesn't
ship with ES5 transpiled sources. If you aim to support browsers like IE11 and below → make sure you
run Babel over your node_modules

In addition, Event is also used. To
be able to run successfully on IE browser, a polyfill is required.

Wouter API


Wouter comes with two kinds of APIs: low-level
React Hooks API and more traditional component-based
API similar to React Router's one.

You are free to choose whatever works for you: use hooks when you want to keep your app as small as
possible or you want to build custom routing components; or if you're building a traditional app
with pages and navigation — components might come in handy.

Check out also FAQ and Code Recipes for more advanced things like active
links, default routes etc.

The list of methods available


Hooks API:

- [useRoute](#useroute-the-power-of-hooks) — shows whether or not current page matches the
  pattern provided.
- [useLocation](#uselocation-hook-working-with-the-history) — allows to manipulate current
  browser location, a tiny wrapper around the History API.
- [useRouter](#userouter-accessing-the-router-object) — returns a global router object that
  holds the configuration. Only use it if you want to customize the routing.

Component API:

- **[``](#route-pathpattern-)** — conditionally renders a component based on a pattern.- **[``](#link-hrefpath-)** — wraps ``, allows to perfom a navigation.- **[``](#switch-)** — exclusive routing, only renders the first matched route.- **[``](#redirect-topath-)** — when rendered, performs an immediate navigation.- **[``](#router-hookhook-matchermatchfn-basebasepath-)** — an optional top-level
  component for advanced routing configuration.

Hooks API


useRoute: the power of HOOKS!


Hooks make creating custom interactions such as route transitions or accessing router directly
easier. You can check if a particular route matches the current location by using a useRoute hook:

  1. ``` js
  2. import { useRoute } from "wouter";
  3. import { Transition } from "react-transition-group";

  4. const AnimatedRoute = () => {
  5.   // `match` is boolean
  6.   const [match, params] = useRoute("/users/:id");

  7.   return <Transition in={match}>Hi, this is: {params.id}</Transition>;
  8. };
  9. ```

useLocation hook: working with the history


The low-level navigation in wouter is powered by the useLocation hook, which is basically a
wrapper around the native browser location object. The hook rerenders when the location changes and
you can also perform a navigation with it, this is very similar to how you work with values returned
from the useState hook:

  1. ``` js
  2. import { useLocation } from "wouter";

  3. const CurrentLocation = () => {
  4.   const [location, setLocation] = useLocation();

  5.   return (
  6.     <div>
  7.       {`The current page is: ${location}`}
  8.       <a onClick={() => setLocation("/somewhere")}>Click to update</a>
  9.     </div>
  10.   );
  11. };
  12. ```

All the components including the useRoute rely on useLocation hook, so normally you only need
the hook to perform the navigation using a second value setLocation. You can check out the source
code of the [Redirect component](https://github.com/molefrog/wouter/blob/master/index.js#L142) as
a reference.

Additional navigation parameters


The setter method of useLocation can also accept an optional object with parameters to control how
the navigation update will happen.

It is not mandatory for custom location hooks to support this, however the built-in
pushState-powered useLocation hook accepts replace flag to tell the hook to modify the current
history entry instead of adding a new one. It is the same as calling replaceState. Example:

  1. ``` js
  2. const [location, navigate] = useLocation();

  3. navigate("/jobs"); // `pushState` is used
  4. navigate("/home", { replace: true }); // `replaceState` is used
  5. ```

Customizing the location hook


By default, wouter uses useLocation hook that reacts to pushState and replaceState
navigation and observes the current pathname including the leading slash e.g. /app/users.

If you do need a custom history observer, for example, for hash-based routing, you can
customize it in a `` component.

As an exercise, let's implement a simple location hook that listens to hash changes:

  1. ``` js
  2. import { useState, useEffect, useSyncExternalStore } from "react";
  3. import { Router, Route } from "wouter";

  4. // returns the current hash location in a normalized form
  5. // (excluding the leading '#' symbol)
  6. const currentLocation = () => window.location.hash.replace(/^#/, "") || "/";

  7. const navigate = (to) => {
  8.   window.location.hash = to;
  9. };

  10. const useHashLocation = () => {
  11.   // `useSyncExternalStore` is available in React 18, or you can use a shim for older versions
  12.   const location = useSyncExternalStore(
  13.     // first argument is a value subscriber: it gives us a callback that we should call
  14.     // whenever the value is changed
  15.     (onChange) => {
  16.       window.addEventListener("hashchange", onChange);
  17.       return () => window.removeEventListener("hashchange", onChange);
  18.     },
  19.     
  20.     // the second argument is function to get the current value
  21.     () => currentLocation()
  22.   );
  23.   
  24.   return [location, navigate];
  25. };

  26. const App = () => (
  27.   <Router hook={useHashLocation}>
  28.     <Route path="/about" component={About} />
  29.     ...
  30.   </Router>
  31. );
  32. ```


useRouter: accessing the router object


If you're building an advanced integration, for example custom location hook, you might want to get
access to the global router object. The router is a simple object that holds current matcher
function and a custom location hook function.

Normally, router is constructed internally on demand, but it can also be customized via a top-level
Router component (see the section above). The
useRouter hook simply returns a current router object:

  1. ``` js
  2. import { useRouter } from "wouter";
  3. import useLocation from "wouter/use-location";

  4. const Custom = () => {
  5.   const router = useRouter();

  6.   // router.hook is useLocation by default

  7.   // you can also use router as a mediator object
  8.   // and store arbitrary data on it:
  9.   router.lastTransition = { path: "..." };
  10. };
  11. ```

Component API


### ``

Route represents a piece of the app that is rendered conditionally based on a pattern. Pattern is
a string, which may contain special characters to describe dynamic segments, see
[Matching Dynamic Segments section](#matching-dynamic-segments) below for details.

The library provides multiple ways to declare a route's body:

  1. ``` js
  2. import { Route } from "wouter";

  3. // simple form
  4. <Route path="/home"><Home />Route>

  5. // render-prop style
  6. <Route path="/users/:id">
  7.   {params => <UserPage id={params.id} />}
  8. </Route>

  9. // the `params` prop will be passed down to
  10. <Route path="/orders/:status" component={Orders} />
  11. ```

### ``

Link component renders an `` element that, when clicked, performs a navigation. You can
customize the link appearance by providing your own component or a link element as children:

  1. ``` js
  2. import { Link } from "wouter"

  3. // All of these will produce the same html:
  4. // Hello!

  5. // lazy form: `a` element is constructed around children
  6. <Link href="/foo" className="active">Hello!</Link>

  7. // when using your own component or jsx the `href` prop
  8. // will be passed down to an element
  9. <Link href="/foo"><a className="active">Hello!</a>Link>
  10. <Link href="/foo"><A>Hello!</A>Link>
  11. ```

If you wrap a custom component with Link, wouter won't install event listeners so make sure the
component handles onClick and href props properly:


### ``

There are cases when you want to have an exclusive routing: to make sure that only one route is
rendered at the time, even if the routes have patterns that overlap. That's what Switch does: it
only renders the first matching route.

  1. ``` js
  2. import { Route, Switch } from "wouter";

  3. <Switch>
  4.   <Route path="/orders/all" component={AllOrders} />
  5.   <Route path="/orders/:status" component={Orders} />
  6. </Switch>;
  7. ```

Check out [FAQ and Code Recipes section](#faq-and-code-recipes) for more advanced use of
Switch.

### ``

When mounted performs a redirect to a path provided. Uses useLocation hook internally to trigger
the navigation inside of a useEffect block.

If you need more advanced logic for navigation, for example, to trigger the redirect inside of an
event handler, consider using
[useLocation hook instead](#uselocation-hook-working-with-the-history):

  1. ``` js
  2. import { useLocation } from "wouter";

  3. const [location, setLocation] = useLocation();

  4. fetchOrders().then((orders) => {
  5.   setOrders(orders);
  6.   setLocation("/app/orders");
  7. });
  8. ```

### ``

Unlike _React Router_, routes in wouter don't have to be wrapped in a top-level component. An
internal router object will be constructed on demand, so you can start writing your app without
polluting it with a cascade of top-level providers. There are cases however, when the routing
behaviour needs to be customized.

These cases include hash-based routing, basepath support, custom matcher function etc.

A router is a simple object that holds the routing configuration options. You can always obtain this
object using a [useRouter hook](#userouter-accessing-the-router-object). The list of currently
available options:

- hook: () => [location: string, setLocation: fn] — is a React Hook function that subscribes
  to location changes. It returns a pair of current location string e.g. /app/users and a
  setLocation function for navigation. You can use this hook from any component of your app by
  calling [useLocation() hook](#uselocation-hook-working-with-the-history).


- matcher: (pattern: string, path: string) => [match: boolean, params: object] — a custom
  function used for matching the current location against the user-defined patterns like
  /app/users/:id. Should return a match result and an hash of extracted parameters. It should
  return [false, null] when there is no match.

- base: string — an optional setting that allows to specify a base path, such as /app. All
  application routes will be relative to that path. Prefixing a route with ~ will make it
  absolute, bypassing the base path.

Matching Dynamic Segments


Just like in React Router, you can make dynamic matches either with Route component or useRoute
hook. useRoute returns a second parameter which is a hash of all dynamic segments matched.
Similarily, the Route component passes these parameters down to its children via a function prop.

  1. ``` js
  2. import { useRoute } from "wouter";

  3. // /users/alex => [true, { name: "alex "}]
  4. // /anything   => [false, null]
  5. const [match, params] = useRoute("/users/:name");

  6. // or with Route component
  7. <Route path="/users/:name">
  8.   {(params) => {
  9.     /* { name: "alex" } */
  10.   }}
  11. </Route>;
  12. ```

wouter implements a limited subset of
[path-to-regexp package](https://github.com/pillarjs/path-to-regexp) used by React Router or
Express, and it supports the following patterns:

- Named dynamic segments: /users/:foo.
- Dynamic segments with modifiers: /foo/:bar*, /foo/baz? or /foo/bar+.

The library was designed to be as small as possible, so most of the additional matching features
were left out (see this issue for more info).

Using a path-to-regexp-based matcher


The `` component accepts an optional prop called `matcher` which allows to customize how a
path is matched against the pattern. By default, a built-in matcher function is used, which
implements basic functionality such as wildcard parameters (see above).

However, if you do need to have more advanced functionality, you can specify your own matcher which
should look like:

  1. ``` js
  2. /*
  3. * accepts a pattern and a path as strings, should return a pair of values:
  4. * [success, params]
  5. */

  6. // returns [false, null] when there is no match
  7. matcher("/users", "/");

  8. // [true, { id: "101" }]
  9. matcher("/users/:id", "/users/101");
  10. ```

Most of the packages for parsing route patterns work with regular expressions (see
[path-to-regexp](https://github.com/pillarjs/path-to-regexp) or a super-tiny alternative
[regexparam](https://github.com/lukeed/regexparam)), so to make it easier for you wouter provides
a factory function for transforming
a regexp-based pattern builder into a matcher. It also makes sure that the expensive transform
operation isn't called on each render by utilizing a simple cache.

  1. ``` js
  2. import { Router } from "wouter";

  3. import makeCachedMatcher from "wouter/matcher";

  4. /*
  5. * This function specifies how strings like /app/:users/:items* are
  6. * transformed into regular expressions.
  7. *
  8. * Note: it is just a wrapper around `pathToRegexp`, which uses a
  9. * slighly different convetion of returning the array of keys.
  10. *
  11. * @param {string} path — a path like "/:foo/:bar"
  12. * @return {{ keys: [], regexp: RegExp }}
  13. */
  14. const convertPathToRegexp = (path) => {
  15.   let keys = [];

  16.   // we use original pathToRegexp package here with keys
  17.   const regexp = pathToRegexp(path, keys, { strict: true });
  18.   return { keys, regexp };
  19. };

  20. const customMatcher = makeCachedMatcher(convertPathToRegexp);

  21. function App() {
  22.   return (
  23.     <Router matcher={customMatcher}>
  24.       {/* at the moment wouter doesn't support inline regexps, but path-to-regexp does! */}
  25.       <Route path="/(resumes|cover-letters)/:id" component={Dashboard} />
  26.     </Router>
  27.   );
  28. }
  29. ```


FAQ and Code Recipes


I deploy my app to the subfolder. Can I specify a base path?


You can! Wrap your app with `` component and that should do the trick:

  1. ``` js
  2. import { Router, Route, Link } from "wouter";

  3. const App = () => (
  4.   <Router base="/app">
  5.     {/* the link's href attribute will be "/app/users" */}
  6.     <Link href="/users">Users</Link>
  7. <Route path="/users">The current path is /app/users!</Route>
  8.   </Router>
  9. );
  10. ```

Note: _the base path feature is only supported by the default pushState and staticLocation hooks. If you're
implementing your own location hook, you'll need to add base path support yourself._

How do I make a default route?


One of the common patterns in application routing is having a default route that will be shown as a
fallback, in case no other route matches (for example, if you need to render 404 message). In
**wouter** this can easily be done as a combination of `` component and a default route:

  1. ``` js
  2. import { Switch, Route } from "wouter";

  3. <Switch>
  4.   <Route path="/about">...</Route>
  5.   <Route>404, Not Found!</Route>
  6. </Switch>;
  7. ```

_Note:_ the order of switch children matters, default route should always come last. If you want to
have access to the matched segment of the path you can use :param*:

  1. ``` js
  2. <Switch>
  3.   <Route path="/users">...</Route>

  4.   {/* will match anything that starts with /users/, e.g. /users/foo, /users/1/edit etc. */}
  5.   <Route path="/users/:rest*">...</Route>

  6.   {/* will match everything else */}
  7.   <Route path="/:rest*">{(params) => `404, Sorry the page ${params.rest} does not exist!`}</Route>
  8. </Switch>
  9. ```


How do I make a link active for the current route?


There are cases when you need to highlight an active link, for example, in the navigation bar. While
this functionality isn't provided out-of-the-box, you can easily write your own `` wrapper
and detect if the path is active by using the useRoute hook. The useRoute(pattern) hook returns
a pair of [match, params], where match is a boolean value that tells if the pattern matches
current location:

  1. ``` js
  2. const [isActive] = useRoute(props.href);

  3. return (
  4.   <Link {...props}>
  5.     <a className={isActive ? "active" : ""}>{props.children}</a>
  6.   </Link>
  7. );
  8. ```


Are strict routes supported?


If a trailing slash is important for your app's routing, you could specify a custom matcher that
implements the strict option support.

  1. ``` js
  2. import makeMatcher from "wouter/matcher";
  3. import { pathToRegexp } from "path-to-regexp";

  4. const customMatcher = makeMatcher((path) => {
  5.   let keys = [];
  6.   const regexp = pathToRegexp(path, keys, { strict: true });
  7.   return { keys, regexp };
  8. });

  9. const App = () => (
  10.   <Router matcher={customMatcher}>
  11.     <Route path="/foo">...</Route>
  12.     <Route path="/foo/">...</Route>
  13.   </Router>
  14. );
  15. ```


Are relative routes and links supported?


Unlike React Router, there is no first-class support for route
nesting. However, thanks to the
base path support, you can easily
implement a nesting router yourself!

  1. ``` js
  2. const NestedRoutes = (props) => {
  3.   const router = useRouter();
  4.   const [parentLocation] = useLocation();

  5.   const nestedBase = `${router.base}${props.base}`;

  6.   // don't render anything outside of the scope
  7.   if (!parentLocation.startsWith(nestedBase)) return null;

  8.   // we need key to make sure the router will remount when base changed
  9.   return (
  10.     <Router base={nestedBase} key={nestedBase}>
  11.       {props.children}
  12.     </Router>
  13.   );
  14. };

  15. const App = () => (
  16.   <Router base="/app">
  17.     <NestedRoutes base="/dashboard">
  18.       {/* the real url is /app/dashboard/users */}
  19.       <Link to="/users" />
  20.       <Route path="/users" />
  21.     </NestedRoutes>
  22.   </Router>
  23. );
  24. ```


Is it possible to match an array of paths?


While wouter doesn't currently support multipath routes, you can achieve that in your app by
specifying a custom [matcher function](#router-hookhook-matchermatchfn-basebasepath-):

  1. ``` js
  2. import makeMatcher from "wouter/matcher";

  3. const defaultMatcher = makeMatcher();

  4. /*
  5. * A custom routing matcher function that supports multipath routes
  6. */
  7. const multipathMatcher = (patterns, path) => {
  8.   for (let pattern of [patterns].flat()) {
  9.     const [match, params] = defaultMatcher(pattern, path);
  10.     if (match) return [match, params];
  11.   }

  12.   return [false, null];
  13. };

  14. const App = () => (
  15.   <Router matcher={multipathMatcher}>
  16.     <Route path={["/app", "/home"]}>...</Route>
  17.   </Router>
  18. );
  19. ```


Can I use _wouter_ in my TypeScript project?


Yes! Although the project isn't written in TypeScript, the type definition files are bundled with
the package.

Preact support?


Preact exports are available through a separate package named wouter-preact (or within the
wouter/preact namespace, however this method isn't recommended as it requires React as a peer
dependency):

  1. ```diff
  2. - import { useRoute, Route, Switch } from "wouter";
  3. + import { useRoute, Route, Switch } from "wouter-preact";
  4. ```

You might need to ensure you have the latest version of
Preact X with support for hooks.


Is there any support for server-side rendering (SSR)?


Yes! In order to render your app on a server, you'll need to tell the router that the current
location comes from the request rather than the browser history. In wouter, you can achieve that
by replacing the default useLocation hook with a static one:

  1. ``` js
  2. import { renderToString } from "react-dom/server";
  3. import { Router } from "wouter";

  4. // note: static location has a different import path,
  5. // this helps to keep the wouter source as small as possible
  6. import staticLocationHook from "wouter/static-location";

  7. import App from "./app";

  8. const handleRequest = (req, res) => {
  9.   // The staticLocationHook function creates a hook that always
  10.   // responds with a path provided
  11.   const prerendered = renderToString(
  12.     <Router hook={staticLocationHook(req.path)}>
  13.       <App />
  14.     </Router>
  15.   );

  16.   // respond with prerendered html
  17. };
  18. ```

Make sure you replace the static hook with the real one when you hydrate your app on a client.

If you want to be able to detect redirects you can provide the record option:

  1. ``` js
  2. import { renderToString } from "react-dom/server";
  3. import { Router } from "wouter";
  4. import staticLocationHook from "wouter/static-location";

  5. import App from "./app";

  6. const handleRequest = (req, res) => {
  7.   const location = staticLocationHook(req.path, { record: true });
  8.   const prerendered = renderToString(
  9.     <Router hook={location}>
  10.       <App />
  11.     </Router>
  12.   );

  13.   // location.history is an array matching the history a
  14.   // user's browser would capture after loading the page

  15.   const finalPage = locationHook.history.slice(-1)[0];
  16.   if (finalPage !== req.path) {
  17.     // perform redirect
  18.   }
  19. };
  20. ```

1KB is too much, I can't afford it!


We've got some great news for you! If you're a minimalist bundle-size nomad and you need a damn
simple routing in your app, you can just use the
[useLocation hook](#uselocation-hook-working-with-the-history) which is only 400 bytes gzipped
and manually match the current location with it:

  1. ``` js
  2. import useLocation from "wouter/use-location";

  3. const UsersRoute = () => {
  4.   const [location] = useLocation();

  5.   if (location !== "/users") return null;

  6.   // render the route
  7. };
  8. ```

Wouter's motto is "Minimalist-friendly".

Acknowledgements


Wouter illustrations and logos were made by Katya Simacheva and