0

I ran into an issue also mentioned here, React-Router re-mounts component on route change, but without any solutions.

If I have a Link pointing to a URL managed by react-router (or react-router-bootstrap in my case),

export default function Navigation(props) {
    return (
        <div id="top-nav">
            <Nav as="nav" aria-label="main" className="container">
                <Nav.Item>
                    <LinkContainer to="/">
                        <Nav.Link><i className="fas fa-home" aria-label="Home"></i></Nav.Link>
                    </LinkContainer>
                </Nav.Item>
                <Nav.Item>
                    <LinkContainer to="/agreements">
                        <Nav.Link>Agreements</Nav.Link>
                    </LinkContainer>
                </Nav.Item>

My Home component resides in a parent Main component which has a switch,

export default function Main(props) {
    return (
        
        <main className="container" id="main">
        
            <Switch>
                <Route exact path="/">
                    <Home />
                </Route>                
                <Route path="/agreements">
                    <Agreements />
                </Route>
                <Route path="/approvals">
                    <Approvals />
                </Route>

and then my Home component (/) has an init (mount) useEffect(..,[]) as

export default function Home(props) {
 
    // On initialization, fetch data
    useEffect(() => {    
        fetchPreliminaryData();
    }, []); 
  
}

then every time click the Home link, I will go into my Initializing/Mounting fetch. I verified that in the debugger. My goal was to only do the fetch the first time the component is ever loaded. This affects the performance of my application. Is there any solution?

gene b.
  • 10,512
  • 21
  • 115
  • 227
  • Whe you say "...every time click the Home link" includes, whereas you're already on Home path? It shouldn't re render... If came from another path to Home, is obvious that useEffect runs. – filoscoder Apr 25 '21 at 16:44
  • It happens which I click `/` (`Home`) from any other URL. – gene b. Apr 25 '21 at 16:47
  • 1
    Then from my understanding of React, it's completely normal. You are from any other path, meaning there is another Component mounted, then you move to `/` (Home) and your `Home` component starts rendering when finish it will call `useEffect` (only once for THIS render) – filoscoder Apr 25 '21 at 16:50

1 Answers1

2

I would store something like this in a global state and fetch it only if it doesn't already exist. However, if you didn't implement such behavior for your project, you could hold this data in the parent component and send it as props together with an onChange function, so that the first time you fetch it, you send the data to the parent component, which will send it back as props, and in the useEffect you can add a condition to fetch the data if props.preliminaryData exists.