1

This a doubt I have regarding the best practice when pushing a new object in an array of objects via setState.

In the below implementation the 'prevObjects' are being spread into the new array to set the state. This passes the references of the old objects, but does not mutate the array or the objects. Hence does that mean the below implementation is good? It is working, but could it be problematic in some edge cases?

const [objArray, setObjArray] = useState([{ name: John }, { name: Jane }]);

setObjArray((prevObjects) => [...prevObjects, newObject])
gerzen
  • 21
  • 2
  • Yes, that's exactly how you do it (that or any of the several similar ways). You've done all the right things: 1. Used the callback form of the state setter so it's always using up-to-date state. 2. Created a new array. 3. Reused objects you aren't changing (rather than creating new ones unnecessarily). Nice one! – T.J. Crowder Feb 24 '22 at 13:01
  • For the avoidance of doubt: In the code above, you *seem* to be calling `setObjArray` at the top level of your component. I don't think that's really what you're doing (I think the second line of code is probably in an event handler or similar), but if you were, that would be incorrect because you'd be causing endless re-renders. But provided the second line of code is in an event handler or similar, you're all set. – T.J. Crowder Feb 24 '22 at 13:04
  • 1
    Thank you, makes sense. And yes, the setObjArray would be in an event handler in a real scenario – gerzen Feb 24 '22 at 15:29

0 Answers0