softshipper
softshipper

Reputation: 34099

Will component Re-Render when the path is changed?

My App component definition looks as follows:

function App() {
    return (
        <Router>
            <Navbar/>
            <Switch>
                <Route path="/howitworks">
                    <HowItWorks/>
                </Route>
                <Route path="/aboutus">
                    <AboutUs/>
                </Route>

                <Route path="/">
                    <Home/>
                </Route>
            </Switch>
            <Footer/>
        </Router>
    )
}

I have a question regarding to route and re-render.

For example, when I route from / to /howitworks, then the component <HowItWorks/> is going to be rendered. Routing back to / from /howitworks, will <Home/> component be re-rendered?

The <Home/> component contains only text. It does not contain any logic.

Update

I have created an example on https://codesandbox.io/s/react-router-forked-2mp45.

When you consider the about component, how it is defined:

import React, { useState } from "react";

const About = () => {
  const [state, _] = useState(2);

  React.useEffect(
    (_) => {
      console.log("state changed");
    },
    [state]
  );

  return (
    <div>
      <h2>About</h2>
    </div>
  );
};

export default About;

and every time when /aboutus is clicked, it shows always the message:

state changed

that means for me, every time when the path changed, then re-render will always happen.

Am I right?

Upvotes: 0

Views: 801

Answers (1)

kooskoos
kooskoos

Reputation: 4879

Yes, re-render happens on path change. Re-render essentially means painting the screen again.

If you think about component being mounting again the component unmounts too on path change.

Here is an example reflecting that https://codesandbox.io/s/react-router-forked-nlqzg?file=/components/About.js

Upvotes: 0

Related Questions