React question detail
How do you prevent mutating array variables?
The preexisting variables outside of the function scope including state, props and context leads to a mutation and they result in unpredictable bugs during the rendering stage. The below points should be taken care while working with arrays variables.
- You need to take copy of the original array and perform array operations on it for the rendering purpose. This is called local mutation.
- Avoid triggering mutation methods such as push, pop, sort and reverse methods on original array. It is safe to use filter, map and slice method because they create a new array.