Use Immerjs with useState hook in React to modify complex states and arrays.
Modifying state in react has been made a breeze with the introduction of the hooks api. Even then, it can be challenging to manipulate arrays and complex state objects: you have to make a copy of the original object first, and then use setState() to set the new value.
The award winning Immerjs package can solve a lot of these complexities.
Quoting the docs,
“ Immer can be used in any context in which immutable data structures need to be used. For example in combination with React state, React or Redux reducers, or configuration management. Immutable data structures allow for (efficient) change detection: if the reference to an object didn’t change, the object itself did not change. In addition, it makes cloning relatively cheap: Unchanged parts of a data tree don’t need to be copied and are shared in memory with older versions of the same state.
useState + Immer
“The useState
hook assumes any state that is stored inside it is treated as immutable. Deep updates in the state of React components can be greatly simplified as by using Immer.”