Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
187 views
in Technique[技术] by (71.8m points)

reactjs - 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?

i.e. 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".

question from:https://stackoverflow.com/questions/66047494/react-native-how-to-optimize-the-rendering-of-flatlists-item-or-doing-non-sh

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]);
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...