I set up a minimal Gatsby page to test when Gatsby re-renders, and I found out that just clicking a regular in-route (hash) anchor link, causes a re-render.
Why is that? Is there any way to prevent it?
Here is an example page:
const SomePage = props => {
console.log('RE-RENDERING PAGE');
return (
<>
<a href="#foo">Link that should not fire re-render</a>;
</>
);
};
There are four reasons why a component would re-render itself: state changes, parent (or children) re-renders, context changes, and hooks changes. There is also a big myth: that re-renders happen when the component's props change.
import { Link } from "gatsby"
const SomePage = props => {
return (
<Link to="#foo">Link that should not fire re-render</Link>;
);
};
<Link>
will render a fully accessible anchor tag with the proper href
.
React re-renders a lot. Since the entire page is wrapped in a Reach Router and you're using a non-memo functional component I'm not the slightest bit surprised you're getting a console message. I was under the impression you were trying to avoid a page reload, not prop-change-based React render.
If you'd like to prevent the re-render, you can use React.memo
:
const SomePage = React.memo(() => <Link to="#foo">Text</Link>)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With