Rendering a JSX variable vs JSX function - what is the difference?


(Hiroki1116) #1

While developing a React Native app, I found piece of code looking like the following.

export default class ItemList extends React.Component {
  constructor(props) {
    super(props);
  }

  renderItem = ({item}) => (
     <View>
       <Text id={item}>{item}</Text>
     </View>
  );

render() {    
  return (
      <View>
        <FlatList
          data={items} //array of strings
          keyExtractor={(item, index) => index}
          renderItem={renderItem}
        />    
      </View>
    );
  }
}

From the code above, I don’t see what renderItem actually is. This is an arrow function returning a JSX.

This code can be changed into something lile…

render() {
  const renderItem = ({item}) => (
     <View>
       <Text id={item}>{item}</Text>
     </View>
  );
  return (
     <View>
        <FlatList
          data={items} //array of strings
          keyExtractor={(item, index) => index}
          renderItem={renderItem}
        />    
     </View>
  );
}

What are the differences between them?
Apologises if this question is too basic, but I’d appreciate if someone could point out the differences between the first and second approch.


(Linesh) #2

I think the two approaches differ more in a performance manner. The second approach will create a new renderItem function each time the render() function is called, and thus FlatList will recognize renderItem={ renderItem } to be receiving a different function each time and trigger a re-render, even if they generate the same results with the same items data.

That shouldn’t be a concern if your data set is small or your component is not frequently re-rendered. You can just go with the way you like. However if the component did cause a performance issue or is becoming the bottleneck of the page, this is something you can optimize to achieve better performance.


(Troy Rhinehart) #3

The first example is not actually valid, a compiler such as babel will move that arrow function into the constructor. By assigning in the constructor however, the function is only created once whereas in the second example the function is created every time render is called.

Pretty trivial performance differences honestly, overall both work fine. Personally however, I’d suggest making renderItem either a static function on the class or change to stateless:

function renderItem({ item }) {
  return (
   <View>
     <Text id={ item }>{ item }</Text>
   </View>
  );
}

function keyExtractor(_item, index) {
  return index;
}

export default function ItemList({ items }) {
  return (
    <View>
      <FlatList
        data={ items } //array of strings
        keyExtractor={ keyExtractor }
        renderItem={ renderItem }
      />    
    </View>
  );
}