0

I'm newbie. And I'm newbie at React. I'm trying react-router. I saw this example: https://reacttraining.com/react-router/web/example/basic.

I reproduced it on Codesandbox.io here: https://codesandbox.io/s/7jxq0j6qp0

I don't understand why the Menu is re-rendering itself when I change URL using menu's links.

enter image description here

If you open console you can see it.

Why?

I think it should not re-render itself. Just the route section. Where am I wrong?

4
  • That's a normal behavior. Your <Menu/> is inside the Router tag, so it'll re-render every time when you change to any route. Commented Jul 4, 2018 at 21:38
  • @MatheusReis it can't be outsdie because I use <Link component. What do you suggest? Commented Jul 4, 2018 at 21:39
  • why you don't want to Menu to be re-rendered? Commented Jul 4, 2018 at 21:58
  • Because is a negative perf impact. This is just a Basic Example. But I also wanna understand. It's a useless re-render! Commented Jul 4, 2018 at 22:05

1 Answer 1

1

You can write your component as PureComponent. Since there is no prop changes right now it won't be re-rendered:

class Menu extends React.PureComponent {
  render() {
    console.log("Menu render() - ", Date.now());
    return (
      <div>
        <ul>
          <li>
            <Link to="/">Home</Link>
          </li>
          <li>
            <Link to="/about">About</Link>
          </li>
          <li>
            <Link to="/topics">Topics</Link>
          </li>
        </ul>

        <hr />
      </div>
    );
 }
}

But, please be aware of the negative sides of this method for other use cases: Dealing with Update Blocking

Sign up to request clarification or add additional context in comments.

5 Comments

Yes, but I don't understand why. PureComponent is heavy because sometimes is better to re-render that check if is to re-render.
I just wanna know why it has to re-render if nothing changes.
It is rerendering because location changes. I know this does not answer your question which is: why it has to.. I think it is better to ask this on React Router's issues section of Github repository.
but it has to do with the link you posted in your answer? The Dealing with Update Blocking one?
It does not explain "why those components are rerendering" it just helps what if we or a third-party library do something causing to block this rerender and we have a problem about routing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.