简体   繁体   中英

React Native - How to optimize the rendering of FlatList's item, or doing non-shallow comparison on extraData?

I am working hard on optimizing my <FlatList /> component, here are my sample codes:


Case 1:

https://snack.expo.io/HrpJli9EE

I am trying to increase the number of id in selectedIds .
However as the selectedIds in context doesn't change reference,
and <FlatList /> is doing a shallow comparison,
so the items didn't re-rendered with the value in context.


Case 2:

https://snack.expo.io/wRLNRYAmU

Therefore I try to make a new object reference every time when the item is pressed,
(Only change line 17 from Case 1's link)
The items can now re-rendered with the new values.
However , the memo() is not working for the <Item /> component,
which may lead to heavy loading for a large list.


So...

Case 1: Is there any way to let <FlatList /> not doing shallow comparison with extraData ?

Or...

Case 2: Is there any way to prevent re-render in the <Item /> component if item value is the same?

ie If I press the first item to increase number,
as the second item and third item's number are not increasing, they should not re-render
but currently, they do re-rendered.

Appreciate any answers or comments.


Reminder: You can open the console panel by pressing "Editor" in bottom bar > enable "Panel" > press "LOG".

Found out using case 2 with useMemo instead of memo can reduce unnecessary rendering of unchanged item:

import React, { useContext, useMemo } from 'react';
import { Text, TouchableOpacity } from 'react-native';

import { styles } from './styles';

const Item = ({ item, onPress }) => {
  const { selectedIds } = useContext(AppContext);
  const value = selectedIds[item.id] || 0;
  const onItemPress = () => onPress(item.id, value + 1);

  return useMemo(() => {
    /* You will only see this console log when this item value is updated */
    console.log("render item", item.id, value);
    return (
      <TouchableOpacity onPress={onItemPress} style={styles.item}>
        <Text style={styles.title}>{item.title} {value}</Text>
      </TouchableOpacity>
    );
  }, [value]);
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM