What’s New in React Router v6?
Find out what’s changed in React Router
React Router is a collection of navigational components that are widely used in almost every React app. It is one of the most popular dependencies in React. The next major version(v6) is yet to be released. It’s still in the beta stage at the time of this writing. Since it’s always nice to explore new features, I’d like to share my thoughts and give you all a sneak peek of the upcoming features and changes to come.
Smaller Bundle Size
React Router v6 is a lot smaller than its predecessor. The size is actually reduced by 60%, which is a good thing. Here is the comparison between the bundle size of v5 and v6 taken from Bundlephobia.
Rendering Components in <Route>
In the previous version, we used to render components by using the
render prop in the
<Route> component. Whenever we needed to pass props to the rendering component, we used the
render prop; otherwise, we used
component. Now, we can achieve both scenarios using a single
As seen in the above snippet, v6 makes it fairly easy to write code without any confusion.
Simpler Nested Routes
Defining nested routes is way easier in v6. Previously, you had to specify the main route in a file, and then the sub-routes in the component rendered by the main route, and so on. Now in v6, you can specify all the routes in one single file, which looks clean and tidy.
As seen above, you needn’t use any string matching or
useRouteMatch function in v6. The syntax is fairly very simple, comparatively.
<Switch> Is Now <Routes>
Previously, we use
<Switch> and wrote
<Route> components within it. Now, we use
<Routes> instead of
<Switch>, though there is no change in the functionality.
Relative Behaviour and Optional exact Prop
In v6, you don’t need to use an
exact prop on
<Route path="/"> anymore. This is because all
<Route> paths match exactly by default. If you want to match more of the URL because you have child routes, use a trailing
*, as in
<Route path="users/*">. All routes and links automatically build upon the
path of the route that rendered them, so, for example, a
<Link to="me"> that is rendered inside a
<Route path="users/*"> is going to link to
useHistory Is Now useNavigate
Oftentimes we programmatically navigate to a different route in our application. That’s when we make use of the
useHistory method, and we use
history.push(<someurl>) in order to navigate to some other component. In v6,
useNavigate is renamed to
useHistory , and we need to use
navigate(<someurl>) instead of using the history` method.
To replace the URL, we can use the same navigation method and pass an additional object as a parameter.
I hope this article has given you an idea of what to expect when version 6 is going to be released! You can read more about React Router v6 in the latest release notes. I hope you enjoyed reading this article.
Thank you for reading!