Problem
I'm trying to put startIndex
in state from within onRowsRendered()
.
This works fine, until CellMeasurer
is put into the mix.
When scrolling down and then up, the following error occurs:
Uncaught Invariant Violation: Maximum update depth exceeded. This can happen when a component repeatedly calls
setState
insidecomponentWillUpdate
orcomponentDidUpdate
. React limits the number of nested updates to prevent infinite loops.
What causes this problem and what solves it?
Demo
- with
CellMeasurer
(error) - without
CellMeasurer
(no error)
Code
import React from "react";
import ReactDOM from "react-dom";
import faker from "faker";
import { List, CellMeasurer, CellMeasurerCache } from "react-virtualized";
import "./styles.css";
faker.seed(1234);
const rows = [...Array(1000)].map(() =>
faker.lorem.sentence(faker.random.number({ min: 5, max: 10 }))
);
const App = () => {
const [currentIndex, setCurrentIndex] = React.useState(0);
const rowRenderer = ({ key, index, style, parent }) => {
return (
<div style={style}>
<div style={{ borderBottom: "1px solid #eee", padding: ".5em 0" }}>
{rows[index]}
</div>
</div>
);
};
return (
<>
<h1>{currentIndex}</h1>
<p>
<em>When scrolling down and then up, an error occurs. Why?</em>
</p>
<List
height={400}
width={600}
rowCount={rows.length}
rowHeight={35}
rowRenderer={rowRenderer}
style={{ outline: "none" }}
onRowsRendered={({ startIndex }) => {
setCurrentIndex(startIndex);
}}
/>
</>
);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);