Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gatsby: Clicking In-Route Anchor Element Leads to Re-Render

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>;
    </>
  );
};
like image 771
Magnus Avatar asked May 09 '19 03:05

Magnus


People also ask

What triggers a re-render?

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.


2 Answers

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.

like image 101
Ram Kishore Avatar answered Oct 24 '22 18:10

Ram Kishore


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>)
like image 25
coreyward Avatar answered Oct 24 '22 16:10

coreyward