Cristian E.
Cristian E.

Reputation: 3583

React Router - Navigating to same route results in re-render

Hi i'm not sure whether this is a desired behaviour or a bug.

This is an empty create-react-app example with react-router-dom

Versions:

There are two routes under the Switch component:

  1. / - for Home component
  2. /contacts - for Contacts component
    import React from "react";
    import { Switch, Route, BrowserRouter as Router, Link } from "react-router-dom";
    
    class Home extends React.PureComponent {
      render() {
        console.log("Home rendered");
        return <h1>Homepage</h1>;
      }
    }
    
    //const HomeMemo = React.memo(Home);
    //const Home = () => <h1>Homepage</h1>;
    const Contacts = () => <h1>Contacts</h1>;
    
    const Header = () => {
      console.log("Header Render");
      return (
        <header className="App-header">
          <Link to="/">Home</Link>
          <br />
          <Link to="/contacts">Contacts</Link>
        </header>
      );
    };
    
    function App() {
      console.log("App Render");
      return (
        <div className="App">
          <Router>
            <Header />
            <Switch>
              <Route exact path="/" component={Home} />
              <Route exact path="/contacts" component={Contacts} />
            </Switch>
          </Router>
        </div>
      );
    }
    
    export default App;

Fiddle available here

Clicking on Home link multiple times results in a Home rendered message.

My assuption was that if we're already on same route it would not attempt to re-render?

Upvotes: 3

Views: 2356

Answers (1)

Cristian E.
Cristian E.

Reputation: 3583

I have raised an associated Github ticket here

And was told by a community member that this is By-Design

The reasons for this design decision remains unknown.

Upvotes: 3

Related Questions