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?
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.