Rokas Lengvenis
Rokas Lengvenis

Reputation: 995

React router keeps unmounting component while pressing on active link

I have a simple app with react router v4.0. There is Home and About links that can be pressed and appropriate Route will be rendered on a page.

I noticed that when clicking on an already active Home link twice or more - Home component gets re-mounted each time which is unexpected behaviour.

This happens only when Route element is not directly in Router but is in a wrapper function App. Ex: https://codesandbox.io/s/wwnxxqy4m5 (press Home link and check console logs)

const Root = () => (
  <Router>
    <App />
  </Router>
);

If I put routes directly to Router component Home is not unmounted each time.

const Root = () => (
  <Router>
    <div>
      <ul>
        <li><NavLink to="/">Home</NavLink></li>
        <li><NavLink to="/about">About</NavLink></li>
      </ul>

      <hr/>

      <Route exact path="/" component={withRouter(Home)}/>
      <Route path="/about" component={withRouter(About)}/>
    </div>
  </Router>
);

Does anyone have ideas, why unmounting of Home is forced when wrapper function is used?

Upvotes: 1

Views: 1520

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281626

The reason that you component is mounted and unmounted again is because to the route you are returning a new component everytime, with component={withRouter(Home)}. So everytime a route path matches, it checks the component prop and each time a new instance of your Home component is created and returned.

In your case you don't actually need to wrap your component with withRouter since the component is directly rendered by the Route and will receive the Route params. However In a case when you need to wrap with withRouter, just create a single instance of a component and then export and import that instance and not create a new one everytime

Working CodeSandbox

Upvotes: 2

Related Questions