Search code examples
reactjsreact-hooksuse-effect

Is there an implementation of infinite scroll with useEffect that doesn't trigger the react-hooks/exhaustive-deps lint warning?


I'm implementing an infinite scroll-like solution using React hooks. The following code shows what I'm trying to accomplish and a working example can be seen on codesandbox here.

I'm receiving an exhaustive-deps warning in useEffect because I haven't listed data as a dependency (this would obviously cause an infinite loop). Is there a way to implement this kind of infinite scrolling solution without suppressing this warning?

function App() {
  const [data, setData] = useState([]);
  const [page, setPage] = useState(0);

  useEffect(() => {
    const newData = getData(page);
    setData([...data, ...newData]);
  }, [page, setData]); // react-hooks/exhaustive-deps warning here

  return (
    <div>
      Data:
      <ul>
        {data.map(el => (
          <li>{el}</li>
        ))}
      </ul>
      <button onClick={() => setPage(page + 1)}>Load More</button>
    </div>
  );
}

Solution

  • You can pass a callback to receive the previous data.

      useEffect(() => {
        const newData = getData(page);
        setData(previousData => [...previousData, ...newData]);
      }, [page, setData]);
    

    Forked sandbox without warnings.
    Edit so.answer.57564952


    Unrelated to the warning above, also make sure to add key prop for each item.

     <li key={el}>{el}</li>