---
title: Router
description: "Basic concepts for navigation and routing in ReScript & React"
canonical: "/docs/react/latest/router"
---

# Router

RescriptReact comes with a router! We've leveraged the language and library features in order to create a router that's:

- The simplest, thinnest possible.
- Easily pluggable anywhere into your existing code.
- Performant and tiny.

## How does it work?

The available methods are listed here:
  - `RescriptReactRouter.push(string)`: takes a new path and update the URL.
  - `RescriptReactRouter.replace(string)`: like `push`, but replaces the current URL.
  - `RescriptReactRouter.watchUrl(f)`: start watching for URL changes. Returns a subscription token. Upon url change, calls the callback and passes it the `RescriptReactRouter.url` record.
  - `RescriptReactRouter.unwatchUrl(watcherID)`: stop watching for URL changes.
  - `RescriptReactRouter.dangerouslyGetInitialUrl()`: get `url` record outside of `watchUrl`. Described later.
  - `RescriptReactRouter.useUrl(~serverUrl)`: returns the `url` record inside a component.

> If you want to know more about the low level details on how the router interface is implemented, refer to the [RescriptReactRouter implementation](https://github.com/rescript-lang/rescript-react/blob/master/src/RescriptReactRouter.res).

## Match a Route

*There's no API*! `watchUrl` gives you back a `url` record of the following shape:

<CodeTab labels={["ReScript", "JS Output"]}>

```res prelude
type url = {
  /* path takes window.location.pathname, like "/book/title/edit" and turns it into `list{"book", "title", "edit"}` */
  path: list<string>,
  /* the url's hash, if any. The # symbol is stripped out for you */
  hash: string,
  /* the url's query params, if any. The ? symbol is stripped out for you */
  search: string
}
```
```js
// Empty output
```

</CodeTab>

So the url `www.hello.com/book/10/edit?name=Jane#author` is given back as:

<CodeTab labels={["ReScript", "JS Output"]}>

```res prelude
{
  path: list{"book", "10", "edit"},
  hash: "author",
  search: "name=Jane"
}
```
```js
// Empty output
```

</CodeTab>

## Basic Example

Let's start with a first example to see how a ReScript React Router looks like:

<CodeTab labels={["ReScript", "JS Output"]}>

```res
// App.res
@react.component
let make = () => {
  let url = RescriptReactRouter.useUrl()
  
  switch url.path {
    | list{"user", id, ..._} => <User id />
    | list{} => <Home/>
    | _ => <PageNotFound/>
  }
}
```
```js
import * as React from "react";
import * as User from "./User.res.js";
import * as RescriptReactRouter from "@rescript/react/src/RescriptReactRouter.res.js";
import * as Home from "./Home.res.js";
import * as NotFound from "./NotFound.res.js";

function App(Props) {
  let url = RescriptReactRouter.useUrl(undefined, undefined);
  let match = url.path;
  if (match === 0) {
    return JsxRuntime.jsx(Home, {});
  }
  if (match.hd !== "user") {
    return JsxRuntime.jsx(NotFound, {});
  }
  let match$1 = match.tl;
  if (match$1 !== 0 && match$1.tl === 0) {
    return JsxRuntime.jsx(User, {
      id: match$1.hd
    });
  } else {
    return JsxRuntime.jsx(NotFound, {});
  }
}

var make = App;

export {
  make,
}
```

</CodeTab>

## Directly Get a Route

In one specific occasion, you might want to take hold of a `url` record outside of `watchUrl`. For example, if you've put `watchUrl` inside a component's `didMount` so that a URL change triggers a component state change, you might also want the initial state to be dictated by the URL.

In other words, you'd like to read from the `url` record once at the beginning of your app logic. We expose `dangerouslyGetInitialUrl()` for this purpose.

Note: the reason why we label it as "dangerous" is to remind you not to read this `url` in any arbitrary component's e.g. `render`, since that information might be out of date if said component doesn't also contain a `watchUrl` subscription that re-renders the component when the URL changes. Aka, please only use `dangerouslyGetInitialUrl` alongside `watchUrl`.

## Push a New Route
From anywhere in your app, just call e.g. `RescriptReactRouter.push("/books/10/edit#validated")`. This will trigger a URL change (without a page refresh) and `watchUrl`'s callback will be called again.

We might provide better facilities for typed routing + payload carrying in the future!

Note: because of browser limitations, changing the URL through JavaScript (aka pushState) cannot be detected. The solution is to change the URL then fire a "popState" event. This is what Router.push does, and what the event watchUrl listens to.
So if, for whatever reason (e.g. incremental migration), you want to update the URL outside of `RescriptReactRouter.push`, just do `window.dispatchEvent(new Event('popState'))`.

## Design Decisions

We always strive to lower the performance and learning overhead in RescriptReact, and our router design's no different. The entire implementation, barring browser features detection, is around 20 lines. The design might seem obvious in retrospect, but to arrive here, we had to dig back into ReactJS internals & future proposals to make sure we understood the state update mechanisms, the future context proposal, lifecycle ordering, etc. and reject some bad API designs along the way. It's nice to arrive at such an obvious solution!

The API also doesn't dictate whether matching on a route should return a component, a state update, or a side-effect. Flexible enough to slip into existing apps.

Performance-wise, a JavaScript-like API tends to use a JS object of route string -> callback. We eschewed that in favor of pattern-matching, since the latter in Rescript does not allocate memory, and is compiled to a fast jump table in C++ (through the JS JIT). In fact, the only allocation in the router matching is the creation of the url record!
