Search code examples
javascriptreactjsmemoization

React JS memoization on list items


If I have a simple app, something like this:

function renderRow(company) {
return DOM.li({
        className: 'item'
    },
    company.title);
}

function renderApp(companies) {
  return DOM.ul({
        className: 'list'
    },
    companies.sort(function(a, b) {
        return a.votes - b.votes;
    }).map(renderRow))
}
var appModel = getCompaniesJSON(100);
renderComponent(renderApp(appModel), document.body);

And I would not want to rerender every list item when a title of a company hasn't changed - is there a way of implementing a shouldComponentUpdate function for the rows(li items)?


Solution

  • It can be done by moving the output of renderRow to a separate <Row title={company.title} /> component. Then you would be able to use shouldComponentUpdate for each row item checking whether or not the prop title has changed:

    In <Row/> component:

    shouldComponentUpdate(nextProps, nextState){
        return nextProps.title !== this.props.title;
    }