Home > Net >  How to avoid rendering FlatList after change state
How to avoid rendering FlatList after change state

Time:10-17

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

CodePudding user response:

onDelete callback should not get any dependencies and use the last state

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

Not seeing any other reason for the whole return to be rerendered beside Button rerender accords onDelete

CodePudding user response:

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.

  • Related