How to avoid rendering FlatList after change state

Viewed 374

I have an array of objects that I display using FlatList .

In my parent component, I have a state isModalDeleteVisible and a button that allows to change this state .

When I press the button (= that I change the state), the whole FlatList is rendering again (I see it at console.log() which is redisplayed).

I understood that a change of state rerend the whole component; I also know that useCallback() helps prevent this by memorizing a function . But in this specific situation I cannot prevent the re-rendering of FlatList

IndexScreen.js :

... 
const IndexScreen = () => {
  const [isModalDeleteVisible, setModalDeleteVisible] = useState(false)

  const onDelete = useCallback(
    () => setModalDeleteVisible(!isModalDeleteVisible),
    [isModalDeleteVisible]
  )

  const listRenderItem = ({ item, index }) => {
    return (
      <Children
        item={item}
        index={index}
      />
    )
  }

  return (
    <Template>
      <Button
        onPress={onDelete}
      />
      <FlatList
        data={dataList}
        renderItem={listRenderItem}
        keyExtractor={(item) => item.id}
      />
    </Template>
  )
}

export default IndexScreen

Children.js :

...

const Children = ({ item }) => {

  console.log(item.id)

  return (
     ...
  )
}

export default Children
2 Answers

In your case useCallback only memoizes the function, which does nothing at preventing rendering FlatList.

If you want to prevent FlatList rerendering as long as its props don't change, then you should use React.memo() for that.

check out flashlist from shopify, it is so fast and it can solve most of your problems. check it out here

Related