reactjsreact-window

Why does react-window re-render the list on every useState event?


I don't understand why react-window does re-render the list on every(all) useState events, which values are not even connected to the list itself. Could someone please explain how this is internally linked and how I can avoid those re-render?

react-window useState re-render

import React, { useState  } from "react";
import { FixedSizeList, areEqual } from "react-window";

function App() {

  const [count, setCount] = useState(0);

  const handleOnClick = () => {
    console.log("PUSHED ME");
    setCount(count+1) // why does it trigger a re-render of FixedSizeList ?
  }

  const Row = React.memo(props => {
    const { index, style } = props;
    return <div style={style}>Row {index}</div>;
  }, areEqual);

  return (
    <div className="App">
      <FixedSizeList
        height={200}
        itemCount={100}
        itemSize={50}
        width={'100%'}
      >
        {Row}
      </FixedSizeList>
   
      <div onClick={handleOnClick}>Push Me</div>
    </div>
  );
}

export default App;

I also tried to use the second react-window areEqual argument, but it didn't helped. https://react-window.vercel.app/#/api/areEqual

Any hints on how this can be solved is highly appreciated! Many thanks in advance!


Solution

  • Move Row outside of App. When a component rerenders all of its variables are redeclared, which means new values except where they have been memoised by a relevant hook e.g. useMemo, useCallback. You are getting a new value for Row on every render.

    React.memo is not a memoisation hook, it is a higher-order component which controls when new props should be passed to a specified component. It should be declared outside of the React render cycle (as should all components) in order to function correctly.