react-apollo-hooks icon indicating copy to clipboard operation
react-apollo-hooks copied to clipboard

Many re-renders... (check with why-did-you-render)

Open frederikhors opened this issue 6 years ago • 2 comments

Using a simple example like the one described here (https://www.leighhalliday.com/react-hooks-with-apollo-graphql):

import { useQuery } from "react-apollo-hooks";

default function StarredRepos() {
  const { data, loading } = useQuery(STARRED_REPOS_QUERY, {
    variables: { numRepos: 25 },
    suspend: false
  });

  if (loading) {
    return <span>Loading...</span>;
  }

  return data.viewer.starredRepositories.nodes.map(node => (
    <Repository data={node} key={node.id} />
  ));
}

and using also https://github.com/welldone-software/why-did-you-render I got these in console:

StarredRepos
{StarredRepos: ƒ} "Re-rendered because of hook changes:"

[hook useMemo result].updateQuery
different functions with the same name.
{prev .updateQuery: ƒ} "!==" {next .updateQuery: ƒ}

[hook useMemo result].stopPolling
different functions with the same name.
{prev .stopPolling: ƒ} "!==" {next .stopPolling: ƒ}

[hook useMemo result].startPolling
different functions with the same name.
{prev .startPolling: ƒ} "!==" {next .startPolling: ƒ}

[hook useMemo result].refetch
different functions with the same name.
{prev .refetch: ƒ} "!==" {next .refetch: ƒ}

[hook useMemo result].fetchMore
different functions with the same name.
{prev .fetchMore: ƒ} "!==" {next .fetchMore: ƒ}

[hook useMemo result]
different objects that are equal by value.
{"prev ": {…}} "!==" {"next ": {…}}

...and other children components...

As you can see many things are re-rendering.

Can you explain it why? And how can I avoid this?

frederikhors avatar May 02 '19 00:05 frederikhors

I can confirm this. I store local state in apollo cache and when I change any property in the state, my components that are subscribed to the store with useQuery rerender even though they are not subscribed to this exact property. I have heavy components like a google map with dozens of markers, so this is a critical matter in my case. Using React.memo helped just to partially avoid the issue (I got 2 unnecessary rerenders of my heavy component instead of 4).

yantakus avatar May 08 '19 12:05 yantakus

Found out this is a duplicate of https://github.com/trojanowski/react-apollo-hooks/issues/36

yantakus avatar May 08 '19 12:05 yantakus