Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add components to list dynamically in React with no redundant render?

Tags:

reactjs

Here is an online sample.

var FruitList = React.createClass({
      render : function() {
        return (
          <div className="container">
            <ul className="list-group text-center">
              {
                Object.keys(this.props.fruits).map(function(key) {
                  count = count + 1;
                  return <li className="list-group-item list-group-item-info">{this.props.fruits[key]+count}</li>
                }.bind(this))
              }
            </ul>
           </div>
         );
       }
     });

I want to add "Cherry" to list. before

As is, it redraws all items redundantly. I hope that orange1 and apple2 need to keep their state with no redraw redundantly.

What the design for dynamic list components is better? after

like image 774
TonyY Avatar asked Sep 19 '17 07:09

TonyY


1 Answers

Extract your list item into it's own pure component, make sure the props only change when the data actually changes, and use the key prop to let react know which item in the list. This way the list will re-render, but the child FruitItem will only re-render when the props change.

import React, {PureComponent} from 'react';

-

class FruitItem extends PureComponent {
  render() {
    console.log('FruitItem render', this.props.name);
    return (
      <li className="list-group-item list-group-item-info">
        {this.props.name}
      </li>
    );
  }
}

-

Object.keys(this.props.fruits).map((key) => {
  return (
    <FruitItem
      key={key}
      name={this.props.fruits[key]}
    />
  );
})

See working codepen, check the console to watch for re-renders

like image 114
Austin Greco Avatar answered Oct 31 '22 22:10

Austin Greco