Skip to content

Instantly share code, notes, and snippets.

@joaovct
Last active January 30, 2022 23:26
Show Gist options
  • Save joaovct/4272bb13fcc089ae042bb453db7bdb71 to your computer and use it in GitHub Desktop.
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
apples = [...apples, "Apple number " + apples.length]
// 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)
// 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 ...
);
});
// 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