Home > Software engineering >  React Infinite scroll, how to not re-render previous items
React Infinite scroll, how to not re-render previous items

Time:08-08

I am new to React so I was wondering. I am creating this component which contains array of 200 items, and I don't want to render those items immediately, that's why I am using Infinite Scroll feature, so that when user nears the end of list new items are rendered. But when that happens because of state changes previous items are also re-rendered, because new array of objects is created. Is there some way to optimize this so only new items are rendered and the previous one remain the same?

This is my Component which uses infinity scroll and displays items:

import styles from "./CountriesSection.module.css";
import { useEffect, useMemo, useRef, useState } from "react";
import { useInfinityScroll } from "../hooks/useInfinityScroll";
import CountriesList from "./CountriesList";

const data = new Array(240).fill({});

const CountriesSection = () => {
  const [currentItemsDisplayed, setCurrentItemsDisplayed] = useState(40);

  const componentsToShow = useMemo(() => {
    return data.slice(0, currentItemsDisplayed);
  }, [currentItemsDisplayed]);

  const divRef = useRef(null);
  let isVisible = useInfinityScroll(divRef);

  useEffect(() => {
    if (!isVisible) return;
    setCurrentItemsDisplayed((prevVal) => prevVal   20);
  }, [isVisible]);

  return (
    <>
      <div className={styles["section-countries"]}>
        <CountriesList countries={componentsToShow} />
      </div>
      <div className={styles.infinity} ref={divRef} />
    </>
  );
};

export default CountriesSection;

Country Card:

import CountryCard from "./CountryCard";
import React from "react";

const CountriesList = ({ countries }) => {
  const countryToCard = (country, id) => <CountryCard key={id} />;
  return countries.map(countryToCard);
};

export default React.memo(CountriesList);

Codesandbox here: https://codesandbox.io/s/gifted-mclaren-qhn4po?file=/src/components/CountriesList.jsx:0-263

CodePudding user response:

You should use React.memo for CountryCard component. codesandbox

If you want to optimize a component(CountryCard) and memoize the result, you wrap it(CountryCard) with React.memo.

Please take a look at React.memo documentation.

  • Related