Advantages of dynamic vs static routing in React

Andrei Khramtsov picture Andrei Khramtsov · Feb 15, 2018 · Viewed 7.7k times · Source

I'm reading about static vs dynamic routing in React Router, and I'm struggling to identify the advantages of the latter (and why v4 chose to go with it). I can see the advantage of listing out all the routes for an application (static), as well as the component that each route maps to, allowing you to trace what would be rendered given a specific URL. But I'm not seeing any clear advantage to dynamic routes.

If anything, I can only see disadvantages, because there is no clear way to see what state a URL will map to, without starting at the root app element and working your way through the routes (though I might be mistaken).

What situations does dynamic routing address? Why is it preferable to static routing (maybe specifically in React apps)?

Answer

Divyanshu Maithani picture Divyanshu Maithani · Feb 23, 2018

Dynamic Routing

From the react router docs:

When we say dynamic routing, we mean routing that takes place as your app is rendering, not in a configuration or convention outside of a running app.

Think of routes as components

The earlier versions of react-router (pre v4) used to have static routes. This led to a centralized routing in apps like:

<Router>
    <Route path='/' component={Main}>
      <IndexRoute component={Home} />
      <Route path='about' component={About} />
      <Route onEnter={verifyUser} path='profile' component={Profile} />
      ...
    </Route>
</Router>

However, this is not exactly the React way of doing things. React focuses on composition using components based logic. So, instead of imagining our Routes as a static system, we can imagine them as components, which is what react-router v4 brings in and the primary philosophy behind it.

Therefore, we can use Route as we would use any React component. This lets us add Route components as and when we build different components. One advantage of doing this is we can decouple the routing logic to the components needing them.

Nesting routes

The About component can handle all the routes and conditionally render parts of UI based on the url (say /about/job or /about/life etc).

Another thing to note is that a Route component will either render the component for a matching route or null. Example, the following Route renders the About component for a route /about and null (or nothing) otherwise.

<Route path='about' component={About} />

This is also similar to how we're used to conditionally rendering components in React:

route === '/about' ? <About /> : null

Now if we need to render some other components inside the About component for routes /about/job or /about/life we can do it like:

const About = ({ match ) => (
    <div>
        ...
        <Route path={`${match.url}/job`} component={Job} />
        <Route path={`${match.url}/life`} component={Life} />
    </div>
)

Dynamic imports and code splitting

Personally, I've also found this approach works better for me in case I'm using dynamic imports with code-splitting, since I can add dynamic routes in any of my components. For example,

import Loadable from 'react-loadable';

const Loading = () => (
    <div />
);

const Job = Loadable({
    loader: () => import('./Job'),
    loading: Loading,
});

const Life = Loadable({
    loader: () => import('./Life'),
    loading: Loading,
});

...

render() {
    return (
        ...
        <Route path={`${match.url}/job`} component={Job} />
        <Route path={`${match.url}/life`} component={Life} />
    )
}

Responsive routes

Another great use case for dynamic routing is creating responsive routes which is explained beautifully in the react router docs and a recommended read. Here's the example from the docs:

const App = () => (
  <AppLayout>
    <Route path="/invoices" component={Invoices}/>
  </AppLayout>
)

const Invoices = () => (
  <Layout>

    {/* always show the nav */}
    <InvoicesNav/>

    <Media query={PRETTY_SMALL}>
      {screenIsSmall => screenIsSmall
        // small screen has no redirect
        ? <Switch>
            <Route exact path="/invoices/dashboard" component={Dashboard}/>
            <Route path="/invoices/:id" component={Invoice}/>
          </Switch>
        // large screen does!
        : <Switch>
            <Route exact path="/invoices/dashboard" component={Dashboard}/>
            <Route path="/invoices/:id" component={Invoice}/>
            <Redirect from="/invoices" to="/invoices/dashboard"/>
          </Switch>
      }
    </Media>
  </Layout>
)

Summarizing the docs, you'll notice how simple and declarative it becomes to add the Redirect to large screen sizes using dynamic routing. Using static routing in such cases would be quite cumbersome and would need us to put all the routes in a single place. Having dynamic routing simplifies this problem since now the logic becomes composable (like components).

Static Routing

There are some problems which are not solved easily with dynamic routing. An advantage of static routing is that it allows for inspection and matching of routes before rendering. Hence it proves useful especially on server side. The react router team is also working on a solution called react-router-config, quoting from which:

With the introduction of React Router v4, there is no longer a centralized route configuration. There are some use-cases where it is valuable to know about all the app's potential routes such as:

  1. Loading data on the server or in the lifecycle before rendering the next screen
  2. Linking to routes by name
  3. Static analysis

Hope this provides a good summary of both Dynamic Routing and Static Routing and the use cases for them :)