I need to keep a large amount of items in state.
Consider
this.setState(oldState => ({
items: [...oldState.items ...newItems]
}))
It creates a new array and copies all the items here, which is slow.
The performant way of adding items would be pushing them on to the old list, but this requires mutating state directly, which may or may not lead to weird bugs.
Lately I moved onto using state like this:
this.setState({
["items"+num]: newItems
})
For example, if num==8
, then we will create a new key in the dictionary "items8
" and set its value to be equal to the array of new items.
I assume in this case React will mutate state to add a new key-value pair (as opposed to creating a new state object). Also, I assume React will pass a reference to the original array, rather than duplicating the array.
Is this a performant way of using React state with a large collection of items? For the purpose of this question, let's assume I am not rendering anything to the DOM.
Edit: I was asked for more context in the comments. I'm working on an open source infinite scroll implementation. It's not for any specific purpose. My data is images and my metadata contains only urls for the image and image thumbnail. However, someone who uses my infinite scroll implementation might use it for a different purpose, like blog posts, or videos, or any other types of items. The general idea is that as the user scrolls down, we fetch metadata for more items, and we want to add that metadata to state. So if someone scrolls very fast, they might cause many state changes per second, and I want those state changes to be fast even if there are many items in state.