Rendering a list pattern

I've been running into variations of this problem concerning the need to create an entirely new data constructs when needing to map through some data to render something: imagine I have an array of items stored as state: const [items, setItems] = useState<string[]>([]); Then I would like to append a string to items, in react I would have to call setItems by creating an entirely new array since react notices that the array has changed and does the rerender again: setItems((prev) => [...prev, newItem]); items.map((item) => <SomeComponent key={item}/ >) this seems really bad for performance if there are many items in the array, is there an alternative way to do this?
10 Replies
barry
barry•2y ago
The worst performance isn't making a new array, the worst is rendering it. If you use something like Tanstack Virtual that helps.
palad1nz0
palad1nz0OP•2y ago
I might be wrong so please correct me but isn't the rendering problem solved by the keys? React will only rerender the new items with new keys while the unchanged items with old keys are skipped.
barry
barry•2y ago
If you don't do any sorts of filtering or changing of order / the order is constant then yeah sure keys solve it Assuming the key is an index and not a uid If the key you've got is a UID you're good
palad1nz0
palad1nz0OP•2y ago
yeah, that was my impression as well, the rendering problem seems to be solved (keys and virtualization) but I'm still a bit uncomfortable by creating an entirely new data construct when needing to mutate a tiny part of it
barry
barry•2y ago
This is just something you have to live with lol You're in React land Immutability kingdom
palad1nz0
palad1nz0OP•2y ago
maybe I should look for another framework 😂
barry
barry•2y ago
I mean, if this is the reason, I would say that's a dumb reason but sure
palad1nz0
palad1nz0OP•2y ago
just joking, i'm just hoping theres a different pattern in react that can handle this case
barry
barry•2y ago
N o p e Immutability rules React (+ Solid) => [...previous, newElement] => previous.filter => previous.map will be around every corner
jingleberry
jingleberry•2y ago
React will get you pretty far until you hit performance concerns. I wouldn’t worry about micro-optimisations such as creating a new array in order to call setState
Want results from more Discord servers?
Add your server