Last active
May 9, 2023 11:13
-
-
Save dipamsen/d2ea767db67c900fbe3824d08eb19fac to your computer and use it in GitHub Desktop.
Why we need to make immutable updates in react
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Why do we need to create copies of state in react? | |
// =================================================================== | |
// Mock state and setState functions | |
let items = [{ name: "item 1", id: "1" }, { name: "item 2", id: "2" }]; | |
const setItems = (newVal) => { | |
// React first checks if the new state passed in has changed or not, from the current state. | |
if (newVal === items) { // only checks for reference, not value! | |
console.log("items has not changed!"); | |
return; | |
} | |
// we arrive here, only if the newVal and items are of different references in memory | |
items = newVal; | |
console.log("items has changed!"); | |
console.log("Updating the DOM..."); | |
}; | |
// ==================================================================== | |
// Demo 1: Without making a copy | |
const demo1 = () => { | |
items[0].name = "updated item 1"; | |
setItems(items); | |
// Output: items has not changed! | |
}; | |
// Demo 2: Making a copy | |
const demo2 = () => { | |
const newItems = items.map((item) => { // map returns a new array | |
if (item.id === "1") { | |
return { ...item, name: "updated item 1" }; | |
} | |
return item; | |
}); | |
setItems(newItems); | |
// Output: items has changed! | |
// Updating the DOM... | |
}; | |
// (only run one at a time) | |
// demo1() | |
// demo2() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment