Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are built-in react native components pure?

I've found in docs that Flatlist, SectionList are PureComponents. There isn't any information about other components (e.g TouchableOpacity). I want to find out which RN build-in component is pure to use useCallback when it's necessary.

If all other components aren't pure it isn't necessary to use useCallback in this example.

export default App = () => {
  const [count, setCount] = useState(0);
  const onPress = useCallback(() => setCount(prevCount => prevCount + 1), [prevCount]);

  return (
    <View style={styles.container}>
      <TouchableOpacity
        style={styles.button}
        onPress={onPress}
      >
        <Text>Press Here</Text>
      </TouchableOpacity>
    </View>
  );
};
like image 693
Stanislav Mayorov Avatar asked Dec 13 '22 08:12

Stanislav Mayorov


1 Answers

TL;DR Flatlist, SectionList, VirtualizedList are React.PureComponent the rest components are React.Component.

How to find which component is using PureComponent

You can check the source code of react-native components on Github either they are using PureComponent or normal Component.

You see TouchableOpacity of React-Native is extended with Component.

TouchableOpacity source

enter image description here

But on the other hand, you can see FlatList uses PureComponent

FlatList source

enter image description here

Also, you can see SectionList is used to React.PureComponent

SectionList source

enter image description here

Here is the Text component of React-Native which is not using React.PureComponent.

Text source

enter image description here

So the conclusion is by default every component extends with React. Component excluding those components which they have mentioned in the docs that they are using React.PureComponent.

Where to use useCallback hook

So as you know, the Pure component is used to optimizing rendering of a class component so if you wanted to optimize functional component, then?

you can use React.memo

useCallback is useful when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders (e.g. shouldComponentUpdate).

Learn about when to use memo or useCallback read this interesting article.

https://kentcdodds.com/blog/usememo-and-usecallback

like image 188
Waheed Akhtar Avatar answered Jan 06 '23 10:01

Waheed Akhtar