Most efficient way of rendering jsx elements when iterating data in reactJS

  • A+
Category:Languages

I am having an array which contains list of objects. I am doing map on this array and rendering the names with span tag.

let data = [{"id": "01", "name": "Hi"}, {"id": "02", "name": "Hello"}]; 

I have been using the below two different functionalities to iterate an array of objects using map and rendering jsx elements.

Functionality1:

import React, { Component } from 'react'; class App extends Component {    render() {     let data = [{"id": "01", "name": "Hi"}, {"id": "02", "name": "Hello"}];     const items = data.map((key, i) => {       return <span key={key.id}>{key.name}</span>;     });     return (       <div>         {items}       </div>     );   } }  export default App; 

Functionality2:

import React, { Component } from 'react'; class App extends Component {    render() {     let data = [{"id": "01", "name": "Hi"}, {"id": "02", "name": "Hello"}];     let rows = [];     data.map((key, i) => {       rows.push(<span key={key.id}>{key.name}</span>);     });     return (       <div>         {rows}       </div>     );   } }   export default App; 

I known to the above two different ways of doing map and rendering jsx elements. Is there any other ways of doing the same apart from these two and which is recommended?

 


I would do this

const data = [{id: 1, name: 'a'}, {id: 2, name: 'b'}];  export default class App extends PureComponent {   render() {     return (       <div>         {data.map(({ id, name }) => <span key={id}>{name}</span>)}       </div>     );   } } 

Now, your data is not reinstantiated on every render, and you don't have to garbage collect any unnecessary variable declarations.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: