PS: This article is originally published on Medium
At the time of writing, React Router v6 is shown on the horizon as an alpha version. Even if it is an early alpha version, there is so much great news to talk about.
As you may already know, there is another great routing solution for React called Reach Router. Reach Router is lightweight, easier to use, and focuses on accessibility. It’s built by one of the core React Router contributors, Ryan Florence. As Ryan mentioned in his mid-2019 blog post, React Router and Reach Router will be merged together and React Router is going to be the surviving project.
We’ve seen the first efforts in v5.1 with Hooks API, but we’re starting to see the actual results with v6: nested routes, relative links, relative routes, automatic route ranking, and so on.
Note: React Router v6.0.0-alpha.2 was used at the time of writing.
Run the following command to get React Router v6:
npm install react-router@6 react-router-dom@6
One of the great improvements over previous versions is the bundle size. It has been reduced by almost 70% from the previous version.
- React Router v5.1.2: 9.4 kb minified + gzipped
- React Router v6.0.0-alpha.2: 2.9 kb minified + gzipped
Michael Jackson, the creator of React Router, explains how they achieved this result:
<Switch> is replaced with
<Routes>. Thanks to this new API, we can define all our routes in one place and have automatic route ranking as well as relative routes and links.
<Route> has undergone some changes to make our lives easier.
<Route component>was removed in favor of
<Route children>was changed to accept child routes.
- No more
<Route strict>since routes are matched automatically.
<Route path>is relative to the route’s hierarchy.
<Link to> is also relative to the route’s hierarchy. If you omit the beginning
/, it becomes relative to the route path that it sits in.
You have the freedom to use multiple
<Routes> in one application. It can be useful to compose small applications to work together.
Do you remember the
react-router-config package that enabled you to define your routes as an object? Well, that package is history. Now we have the
useRoutes hook instead.
It’s similar to the old package with a few improvements. You define your routes as an array of objects, pass it to the custom hook, and you get a React element that you can render. That’s it.
Here is an example configuration:
I hope it’s not going to be a surprise for you if I say
<Routes> is just a wrapper component over
useHistory is now history. It’s been replaced with React’s suspense-ready navigate API. From now on, you can
useNavigate to navigate around. It has both imperative and declarative options.
More and more details will surely come in the following days. No matter what, I’m already happy with what I see.