Technology Blog

Look deep into latest news and innovations happening in the Tech industry with our highly informational blog.

What’s new in React Router 6

hkis

React Router is by far the most popular library in the React ecosystem. According to npm, it is downloaded about 3.6 million times a week. This number is almost half of React’s 7.6 million weekly downloads. This means that almost every second project that uses React uses React Router.

That’s huge. Almost half of the React projects out there rely on React Router for routing. Chances are, if you have worked with React, you have worked with React Router.
Now with version six in beta and a new release coming soon, we thought it would be interesting to take a dive into what’s new and what has changed in React Router version 6.

React Router is not without controversy

For a library that is so important to the React community, it has gone through a number of iterations and breaking changes. From its first release in 2014, and with every major release, the maintainers of React Router have introduced new features and breaking changes. Some in the React community have complained about the difficulty of upgrading from one version to the next, and have questioned the library’s constant churn.

Many have complained about the difficult upgrades that came with every new major release of the library.

Not everyone needs to upgrade

If your application is working correctly, and you don’t need access to the new features promised in version 6, you can stick with your older version. Don’t feel the need to refactor your old applications to use React Router 6. If it ain’t broke, don’t fix it.

Installation

npm install react-router@next react-router-dom@next

What’s new

So without further ado, let’s take a look at what’s new and what has changed in the latest version of React Router

Routes Replaces Switch

Routes is introduced as a new element in React Router version 6. This new element allows us to easily define nested routes and relative routes, and make it easy to compose complex routes and layouts. In the previous version of the library, we defined Routes inside of a Switch.

The <Routes > is the new <Switch> element now. It is very much similar to <Switch> with some new features.

// old - v5
import { BrowserRouter, Switch, Route } from 'react-router-dom';
const App = () => {
  return (
    <BrowserRouter>
      <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/users" component={Users} />
      </Switch>
    </BrowserRouter>
  );
}
// new - v6
import { BrowserRouter, Routes, Route } from 'react-router-dom';
const App = () => {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="users" element={<Users />} />
      </Routes>
    </BrowserRouter>
  );
}

Did that component prop got changed to element?
That brings us to our second highlight.

<Route component> is replaced with <Route element>

If you notice in the above example, in the new version we are passing a react element instead of a component. This is so much better, now we can pass props directly to the element.

// old - v5
<Route exact path="/" component={Home} />
<Route path="/users" render={routeProps => (
    <Users isCustomLayout={true} />
  )}
/>
// new - v6
<Route path="/" element={<Home />} />
<Route path="users" element={<Users isCustomLayout={true} />} />

Routes and Links are relative to their parent

Now, all Route and Link children of a Route are relative to their parent. This makes it a lot easier to build applications with many nested routes and makes it easier to reason about your application’s routing logic.

No more exact and strict props
Yes, you read it right. In v6 all the routes match exactly by default.

// old - v5
<Route exact path="/" component={Home} />
// new - v6
<Route path="/" element={<Home />} />

Relative paths and links
In v6, both paths and links are relative to their parent route. This means we can omit the “/” if we want the relative path.

// old - v5
<Route exact path="/" component={Home} />
<Route path="/users" component={Users} />
// new - v6
<Route path="/" element={<Home />} />
<Route path="users" element={<Users />} />

If you have used previous versions of React Router, you will immediately notice that we don’t need to use the exact prop anymore. You will also notice that the Link we defined is relative. Instead of passing /customers/:id, we can just use /:id.

What about nested routes then? They just got better.

Easier Nested Routes

Just like your regular react elements we just need to wrap the child route with a parent one.

// old - v5
<Route exact path="/" component={Home} />
<Route path="/users" component={Users} />
// ....
users.js
import { useRouteMatch } from 'react-router-dom';
const Users = () => {
  const { path } = useRouteMatch();
return (
    <div>
      // you can do something here
      <Switch>
        <Route path={`${path}/:id`} component={UserInfo} />
        <Route path={`${path}/profile`} component={UserProfile} />
      </Switch>
    </div>
  );
}
// new - v6
<Route path="/" element={<Home />} />
<Route path="users" element={<Users />}>
  <Route path=":id" element={<UserInfo />} />
  <Route path="profile" element={<UserProfile />} />
</Route>
// ....

import { Outlet } from 'react-router-dom';
const Users = () => {
  return (
    <div>
      // you can do something here
      // Outlet: This element is used as a placholder for the child route.
      // Which means it will be either <UserInfo /> or <UserProfile />
      <Outlet />
    </div>
  );
}

Object-based routes

Now we can define our routes using the new useRouter hook. This allows you to build your routes using JavaScript objects. Let’s take a look at our previous application, now defined using useRouter.

import {
  BrowserRouter,
  Link,
  Outlet,
  useRoutes
} from 'react-router-dom';

function App() {
  let element = useRoutes([
    { path: '/', element: <Home /> },
    {
      path: 'customers',
      element: <Customers />,
      children: [
        { path: '/', element: <CustomersIndex /> },
        { path: ':id', element: <CustomerProfile /> },
      ]
    }
  ]);

  return element;
}

function Users() {
  return (
    <div>
      <nav>
        <Link to="/1">Customer 1</Link>
      </nav>

      <Outlet />
    </div>
  );
}

You might ask yourself, why does it matter? Why would I want to compose my routes using JavaScript objects instead of JSX? One great use case would be to programmatically build routes, let’s say, based on the directory structure of your application. You could loop through all of the files in your pages directory, and build routes from that.

Smaller Bundle Size

The team behind React Router claims that the new version is a lot smaller than the previous versions. They estimate that it’s about 70% smaller. Smaller bundles mean that your application loads faster, and content to your users faster.

With all these awesome changes, there is also icing on the cake. They have reduced the bundle size by more than 50%.

Pic courtesy: medium.com

Suspense Ready Navigation

The old useHistory hook has been removed and replaced with a suspense-ready navigate API. Now you can use useNavigate to programmatically navigate around your application. They also expose a Navigate component that you can use to redirect your users.

No more history, it’s time to navigate. The useHistory hook is now replaced with the suspense-ready useNavigate hook.

// old - v5
import { useHistory } from 'react-router-dom';
const CustomButton = props => {
  const history = useHistory();
  const handleClick = () => {
    history.push('/users');
  }
  return <button onClick={handleClick}>{props.label}</button>;
}
// new - v6
import { useNavigate } from 'react-router-dom';
const CustomButton = props => {
  const navigate = useNavigate();
  const handleClick = () => {
    navigate('/users');
  }
  return <button onClick={handleClick}>{props.label}</button>;
}

So that’s it! If you believe that your applications can benefit from smaller bundle sizes, and from suspense ready navigation, we strongly suggest that you upgrade to the latest version.

For more information and to develop web application using React JS, Hire React Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft”. To develop custom web apps using React JS, please visit our technology page.

Content Source:

  1. medium.com