Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Array
- // Copy array [...arr]
- // Merge arrays [...a, ...b]
- // Add elements [1, ...arr, 4]
- // In React state setState([...old, newValue])
- // Object
- // Copy { ...obj } New object, same values
- // Add/Update { ...obj, key: value } New or updated property added
- // Merge { ...obj1, ...obj2 } Combines both (right one wins on key)
- // Immutability Used in state updates Avoids mutation of original object
- // React
- const [user, setUser] = useState({ name: "Alice", age: 25 });
- setUser(prev => ({ ...prev, age: 26 }));
- // Shallow Copy Warning
- const obj1 = { user: { name: "Alice" } };
- const obj2 = { ...obj1 };
- obj2.user.name = "Bob";
- console.log(obj1.user.name); // "Bob" ❗️
- // Spread only makes a shallow copy, not deep clone. Nested objects are still shared.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement