In React, it is generally considered a best practice not to mutate the state variable directly. Instead, you should use the setState method provide...
For further actions, you may consider blocking this person and/or reporting abuse
What has never been particularly clear to me is where to draw the line on immuatbility. Let's say I have a customer object with an array of order objects and I need to update one of the orders. Do I just replace the order, the array of orders or the whole customer object. The latter seems very expensive for a single element of a single object in a nested array.
If my State has a customer and a courier and a finance company, can I just replace the customer or do I need to replace the entire State.
When dealing with nested objects or arrays, it's generally recommended to maintain immutability at all levels. If you have a customer object with an array of order objects, and you need to update one order, you should create a new array with the updated order and use that to update the customer object. Similarly, if you need to update a property within an order object, create a new order object with the updated property and use it to create a new array of orders.
So in React specifically is every useState() creating a separate top level object or can the hook relate to a nested object.
I e. Could my useState refer to customer.orders and any setState(orders) would then also fire updates on the customer state too?
In React, the useState hook is used to create a state variable and its associated setter function. Each call to useState creates a separate state variable, and these state variables can hold different data types, including nested objects.
In general, I agree on the concept of avoiding mutating data where possible. In one project I previously worked on, we used immutable-js to help with making data immutable.
Nice, I have not used immutable-js yet, will try in future, thanks for suggesting
Great, concise post, Ujjawal!
This can save junior developers a lot of time because it's one of the most common mistakes they make early on with React.
What do you think are some other common mistakes they make besides mutating the state directly?
Thanks so much
This is important for whole javascript ecosystem. If you mutate anything the pointer stays in memory and garbage collector cant remove it from memory, its nit just for React 🙂
Great Post 🧡
thanks
Immutability is certainly a quick way to test if two objects are the same or not, that can be an expensive operation. There are downsides though, garbage collection is not free and in rapid changing updates it's important to optimise for this to avoid glitches and stalls caused by constantly allocating and copying data.
The React useState mechanism can be pressed into service to give fine grained control over re-rendering while mutating underlying data structures and this can be optimal if the copying of a large data structure is required to maintain immutability.
Nice Read