Last active
January 30, 2022 23:26
-
-
Save joaovct/4272bb13fcc089ae042bb453db7bdb71 to your computer and use it in GitHub Desktop.
Artice: Mobx likes mutability. React does not | With Mobx you can mutate your state
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
apples = [...apples, "Apple number " + apples.length] |
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
// Let's say you have an user state | |
const user = observable({ | |
name: "" | |
}); | |
// For updating its name, just mutate the state inside an action | |
// by assigning a new value for the property you want to change: | |
const setName = action((name, user) => { | |
user.name = name | |
}) | |
setName("New cool name", user) |
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
// Mind that in this example we're only using the persons state | |
// and wrapping our component with the observer | |
const Persons = observer(({ persons }) => { | |
useEffect(() => { | |
console.log("Current state of the list: ", persons); | |
}) | |
return ... | |
); | |
}); |
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
// Don't ❌ | |
useEffect(() => { | |
console.log(`The person's name is ${person.name}`) | |
},[person]) | |
// Do it ✅ | |
useEffect(() => { | |
console.log(`The person's name is ${person.name}`) | |
},[person.name]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment