React & Modern Frontend (445 Qs)•Part 8: Advanced React Patterns, Portals & Performance (152 - 261)
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.
Practical Code Example
javascript
// Preventing mutating array state:
const [items, setItems] = useState([1, 2, 3]);
// WRONG: items.push(4); (Mutates original!)
// CORRECT: setItems([...items, 4]); (New array reference)