Adding an event listener to a lot of elements in React

I had a component CategoryPicker

that displays a large category tree (hierarchical, about 20,000 nodes), each of the node tied to an event handler onClick

to figure out which node the user clicked on.

When installing this component very slowly, the profiling result shows that it EventPluginHub.putListener

consumes most of the resources.

The only solution I can think of is to use jQuery to bind an event handler to its predecessor, you know, old school. But apparently this is against the React design philosophy.

const CategoryPicker = React.createClass({
  render() {
    return (
      // data has about 20,000 elements
      {data.map((d) => {
        return (
          <div onClick={this.handleClick.bind(this, d.cateId)} key={d.cateId}>
            {d.cateName}
          </div>
        );
      });}
    );
  }
});

      

profile result

Update

I tried to remove the event handler onClick

on the nodes, the performance improvement is obvious. I guess I should use the jQuery way to solve this situation right now.

+3


source to share


2 answers


Ideally, you should attach an event handler to the parent component (just using react, no jQuery needed) and let those events bubble up. Then you can use the passed event object to determine which component was clicked.



If for some reason you want to avoid this, also consider the fact that it itself bind

will cause a lot of overhead. You are essentially creating a new function with each component.

+1


source


Today I came across code that globally fit this "bubbling onClick on parent, data attributes on children" strategy. It hurts so much to read. I would suggest using a virtual rendering system like response-table to only render a few categories visible to the user. You get a real performance boost because you just don't represent 90% of your 20,000 divs to begin with. And it solves the problem of an event listener with associated functions that use memory.



0


source







All Articles