You’re right that using the store in this way makes the state only accessible inside the component. In this example that’s what I was trying to demonstrate, since sometimes you will want the state to be encapsulated in the component to improve modularity.
Totally agree. I first thought about how you could implement this without mobx but there are several issues that I couldn’t find any practical way to solve. Pulling in mobx not only solves those problems, but actually improves the interface.
Thanks for the response.
You’re right, technically mobx still has to tell your React components to rerender when the state changes, and it looks like behind the scenes it currently uses forceUpdate: https://github.com/mobxjs/mobx-react/blob/73120d88cc86d2a22d36c42d385959aa396b9a8d/src/observer.js#L195
That means take the prop called whatever the value of the variable
propName is, and assign it to a variable called
callback. It’s equivalent to
const callback = this.props[propName];. In that method it is used so you can name the callback whatever you want, like
onClick, instead of having to call it
The if statement just checks if an
onClick prop was provided to the component. If not, the button will log the click (line 3) but do nothing else.
Line 8 calls the
onClick prop that was passed in with any arguments that the
logOnClick function is called with. In this case, that would be an…