React Router v6

Tram Ho

React Router v6 is being gradually improved and will be released in the near future.

Let’s find out through the positive changes of this v6 version compared to the previous version (v5) okay (go)

1. <Switch> is becoming <Routes>

Component top-level Component changed its name from <Switch> to <Routes> , but mostly its old functionality remained the same.

With React Router v6, we just need to change it with <Routes>

2 Big Changes with <Route>

In v6 <Route> seems to receive the most changes, new changes make the use and understanding become much simpler.

The props component or render in v5 will be changed to element


  • Also <Route exact /> has been omitted, because all <Route> paths are by default exact . If you want to create a path for multiple <Route> with many customizations, you can use the * sign similar to the example above <Route path="profile/*" element={<Profile />} />
  • Note <Route path> patterns

React Router v6 uses a simple format that only supports one type of dynamic URL :id and * , with * only at the end of the url, not in the middle

Valid route formats in v6:

Routes written in RegExp structure will not be valid in v6:

The removal of the structure written in RegExp help decrease the file size and makes syntax bundle of Route simpler, more readable

3. Nested Routes are Simpler

Nested routes in v5 require you to specify the url to be able to render the component correctly, requiring the use of string-matching logic (for example, combining strings), for example:

With React Router v6, you can skip the string-matching logic ( match.path as above), nor do you need to use useRouteMatch() hook. Your code will be much easier to read:

Note: the <Outlet> component is used like {this.props.children} in React Router v6. This was a very popular feature from Reach Router!

  • Note: The <Outlet> component is used similarly to {this.props.children} in React Router v6.

4. useNavigate Instead of useHistory

With previous versions we often used history in hook useHistory to navigate. But in this React Router v6, useHistory has been renamed to useNavigate

history.push() will be replaced with navigate() :

In some cases, we want to change the URL, not push the new URL:

For the case you often use go , goBack , goForward of useHistory , with useNavigate , everything is simplified:

With v6:

5. From 20kb to 8kb

More than all of these changes, React Router v6 is smaller and only 50% lighter than the previous v5 version. Lighter means it will load and load libraries faster. Too great. [email protected] [email protected]

6. Summary

Through the above article, I want to introduce the highlights of React Router v6 compared to the current version, v5, hoping to help everyone.

Let’s wait for the official release of React Router v6, release note

Thanks for watching.

7. References

React Router v6 Preview

React Router v6 in alligator

Migrating React Router v5 to v6

Share the news now

Source : Viblo