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
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
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
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.