React: Don't render components in table who aren't visible

Johannes Klauß picture Johannes Klauß · Feb 10, 2017 · Viewed 9.1k times · Source

I have a table with >30 rows and >50 columns. Each row and each cell is a specific React component, since you can manipulate them and they change behaviour and look based on changing data.

So my component hierachy looks like this:

Grid -> Row -> Cell

I am using MobX to handle the application state and it seems to slow down a bit, when it comes to state changes that affect some cell components. Since not every cell and row is visible to the user (the table is scrollable) I thought that it might be an performance improvement to only let React components that are actually visible.

I wondered if there might be an existing component or how I would approach creating such a component in a performant way.

Also I recognized that cells und rows rerender every time the state changed. Maybe it has something to do with the fact, that every cell and row component injects the appStore. How do I tell MobX that it should only rerender those changed components? Is that even possible?

So basically I am looking for either way.

Answer

Daniel picture Daniel · Feb 10, 2017

I'd go with react-visibility-sensor.

Something like:

const VisibilitySensor = require('react-visibility-sensor');

class TableRow extends React.Component {
    onChange(isVisible) {
        this.setState({ isVisible });
    };

    render () {
        const { isVisible } = this.state;

        return (
            <VisibilitySensor onChange={onChange}>
                {isVisible && {/* Table row content */}}
            </VisibilitySensor>
        );
     }
}