React creates single-page applications. In single-page applications, it is important to display multiple views without having to reload the browser. React Router plays an important role in managing this. It is the most popular lightweight, fully-featured routing library for React.
The latest release of React Router 6, has created a lot of buzz in the React community.
In this blog, we will look into some of the new changes in React Router 6.
More compact and elegant
React Router v6 was built from scratch using React hooks. It helped the v6 code to be more compact and elegant than the v5 code.
Smaller bundle size
In v6 the minified gzipped bundle size dropped by more than 50% ! React Router now adds less than 4kb to our total app bundle. With tree shaking enabled, the actual results will be even smaller.
Routes replaces Switch
<Switch> is replaced with
Routes component has a new prop called
where we can pass the component it needs to render.
Instead of scanning the routes in order,
<Routes> automatically picks the best one for the current URL.
Let us take the example of Blogs.
The way these routes are ordered matters a lot if we are using
The Route element with param
slug will also catch the
Blog component will be rendered instead of
We can probably fix this issue by adding
exact to the
Now let’s modify the same example to use
With this change, we don’t need to worry about the order anymore
Routes picks the most specific routes first based on the current URL.
Earlier, we had to specify the entire path in the
But now, the path of a
Link is relative to the path of
Route that rendered it.
Link in the above example will link to
because it’s rendered inside
Also, we don’t need to change the path if we ever change the parent URL.
Keep in mind that Relative
<Link to> values do not begin with
With React Router 6, we can now nest our Routes inside one another, and their paths will nest too.
It makes our layout code more manageable.
Another way to think of index routes is that it’s the default child route when the parent matches but none of its children do. Mostly we might not need an index route. But, if there is any sort of persistent navigation in the parent route we’ll most likely want index route to fill the space when the user hasn’t clicked one of the items yet.
This allows the
Blogs to render by default at
- Absolute paths still work in v6 to help upgrade easier.
- We can ignore relative paths altogether and keep using absolute paths forever if we would like to.
Check out more details about all the cool stuff that has been added to React Router on the official blog.