Switch Component in React Router

Akshay Waingankar
3 min readMay 29, 2021

--

Routing is one of the major parts of React Js application and it needs to be perfect so it will display proper results to the end-user.

First, we will check how normal route works

import {BrowserRouter as Router,Route,withRouter,Switch,Link,hashHistory,} from "react-router-dom";import Home from "./Components/Home";import Vegetables from "./Components/vegetables";import Flowers from "./Components/Flowers";function App() {return (<div><h1>React Application</h1><Router><ul><li><Link to="/">Home</Link></li><li><Link to="/vegetables">Vegetables</Link></li><li><Link to="/flowers">Flowers</Link></li></ul><Route exact path="/" component={Home}></Route><Route path="/vegetables" component={Vegetables}></Route><Route path="/flowers" component={Flowers}></Route></Router></div>);}export default App;

In this way, the application will go through all the routes and display the output which happens to be a problem. Even after a matching route is encountered it will still check for the next route. This is redundant and affects the performance. For justification will render /vegetable route twice

<Route exact path="/" component={Home}></Route><Route path="/vegetables" component={Vegetables}></Route><Route path="/flowers" component={Flowers}></Route><Route path="/vegetables" component={Home}></Route>

In the above example, the route checked /vegetables and it found it once still down and found another one after /flowers which return Home component.

There will be a possibility that the developer writes the same route more than once or has more routes that may cause performance issues.

To overcome this issue we can use the switch route

<Router><ul><li><Link to="/">Home</Link></li><li><Link to="/vegetables">Vegetables</Link></li><li><Link to="/flowers">Flowers</Link></li></ul><Switch>     <Route exact path="/" component={Home}></Route>     <Route path="/vegetables" component={Vegetables}></Route>     <Route path="/flowers" component={Flowers}></Route>     <Route path="/vegetables" component={Home}></Route></Switch></Router>
Output with switch route

As we know the feature of switch syntax, it will stop proceeding once it will find a match. Same thing happens over here. Even we pass Home component twice with /vegetables route, it will return only once and stop proceeding afterwards.

If you like this article, don’t forget to clap and share your response in the comment section. Thank you!😊

--

--

No responses yet