notElonMusk
notElonMusk

Reputation: 374

fetchMore causes page to re-render unexpectedly

I have an infinite scroll list. I recently updated to the latest Apollo client and noticed infinite scroll no longer works.

Upon deeper investigation. I noticed when I call fetchmore with the incremented skip, it causes the entire page to re-render. Any ideas?

Query:

   const {
      data,
      loading: queryLoading,
      fetchMore,
      error,
      networkStatus
    } = useQuery(SEARCH_PROFILES, {
      variables: { ...searchParams, skip: skip.current },
      fetchPolicy: "cache-first",
      notifyOnNetworkStatusChange: true
    });

FetchMore

 const fetchData = () => {
      ErrorHandler.setBreadcrumb("Fetch more profiles");
      skip.current =
        skip.current + parseInt(process.env.REACT_APP_SEARCHPROS_LIMIT);
      const intLimit = parseInt(process.env.REACT_APP_SEARCHPROS_LIMIT);

      if (hasMore.current) {
        fetchMore({
          variables: {
            searchType,
            long,
            lat,
            distance,
            ageRange,
            interestedIn,
            skip: skip.current,
            limit: intLimit,
            isMobile: sessionStorage.getItem("isMobile")
          },
          updateQuery: (previousResult, { fetchMoreResult }) => {
            if (!fetchMoreResult) {
              hasMore.current = false;
              return previousResult;
            } else if (
              fetchMoreResult.searchProfiles.profiles.length < intLimit
            ) {
              hasMore.current = false;
            }
            const newData = produce(previousResult, (draftState) => {
              if (draftState.searchProfiles.profiles) {
                draftState.searchProfiles.profiles.push(
                  ...fetchMoreResult.searchProfiles.profiles
                );
              } else {
                draftState.searchProfiles.profiles =
                  fetchMoreResult.searchProfiles.profiles;
              }
            });

            return newData;
          }
        });
      }
    };

Upvotes: 4

Views: 1300

Answers (1)

ndotie
ndotie

Reputation: 2150

Well, From your explanation, re-rendering is necessary since you're loading new content on while you scroll, but for entire page not to be re-rendered is what we're concerned here... below tips might help.

  1. extract the part of the page which needs to fetch data on scroll into a separate component, since it will be the only component which needs to be re-rendered
  2. wrap your extracted component with React.memo() so it doesnt re-render when there is no change on data.
  3. Make good use of life cycle hooks methods, they're the tools to manage on where or how to re-render

Upvotes: 1

Related Questions