push to array render
Unanswered
Siberian posted this in #help-forum
SiberianOP
Hi there. I wonder if there is possible to push element to the array that is rendered on the screen without creating completely new array for that. Im trying to do that with useState, but if thats wrong just let me know
25 Replies
but for sure, we need more details for it
SiberianOP
well for now im doing
setNewItem(item => [...item,newItem]) maybe im wrong but it creates a new array with old items and a new item at the end = rerenders whole array on screen?Dunker
yep, you shouldnt mutate state at all
this is way to go
also state updates lead to rerenders to make sure evertyhing are okay
SiberianOP
So with big realtime data I need to somehow overcome full array rerender?
Dunker
memoizing
SiberianOP
in some simpler explanation?
Dunker
how are you setting your state
SiberianOP
const [firestoreDatabase, setFirestoreDatabase] = useState<any[]>([]);and then in my useEffect that watches for data in realtime db
setFirestoreDatabase((old) => [...old, data]);and then just
{firestoreDatabase.map((post, index) => (//HTML CODE//)Dunker
what is wrong with it
@Dunker what is wrong with it
SiberianOP
isnt that rerendering whole array again instead of just adding one?
Dunker
when you add new item, your array being new array so it rerenders
but its the working way of react
SiberianOP
that might be problematic with realtime database that might get big enough to lag
but thanks, I will try finding other way than using useState
Dunker
you cant set things without state tho
we can say VDOM preventing you from going
i could recommend a thing, make a performance test to your DEV server via Profiling at DevTools
and see that which things rerendering when you add items
then try to wrap that components or state with memo, callback or anything
thus you can find what causes rerender and why
also if you have big data, its better to split them into routes, pages or maybe apis
finally, if you are rendering a long list and having problems with speed, its better to look for "react-window" kind of libs, "virtual rendering"
finally, if you are rendering a long list and having problems with speed, its better to look for "react-window" kind of libs, "virtual rendering"
SiberianOP
well thats sad. But thanks, I guess I will have to leave it like that or use react-window after looking this one up