Hacker News new | ask | show | jobs
by cloverich 2082 days ago
(Thinking in terms of local stores)

> how do your 'not connected' stores know when, say, a user logs out?

If they need this information, it can be passed in from above, or pulled from context. But unless the store and component need to stay mounted when user logs out, they might not need to do anything. There's nothing wrong with a local store being created by a component that receives props and provides them via constructor arguments.

> write code, bespoke to each object, to be able to reset these objects too?

I almost never do this, and nearly always create a new store when the component mounts. The combination of `useLocalStore`[1] with mobx-react-lite makes this straight forward. So per the above example, your component could `useLocalObservable(() => new Store(props.user))`

[1]: https://mobx.js.org/react-integration.html

1 comments

To be honest I don't understand why people use mobx this way. I mean short life store objects, populated by props, that are recreated every mount. Might as well just use React state and save the overhead. You might say, because I have several components using the same business logic and fields and such, I can inject the same store into multiple components. I would say that logic can go in functions which take React state as their argument. You don't need a global state management tool to separate business logic from the view.
> Might as well just use React state and save the overhead. Unless you mean conceptual overhead (i.e another library), it should be less overhead with mobx because there's no need to re-create objects on every re-render, and further re-renders in general are less common (since mobx precisely controls renders for you). Also localStore's need not be short lived by definition, just local. I have a notes app where the main components localStore stays mounted for (literally) days :)
It's more overhead in the sense that mobx needs to walk all your store objects and check for changes, on top of what React does. Anyway that's fine if you really need that precision. I just useMemo at the 'hotspots' and that is enough. Remember also that if vdom diffing doesn't pick up a change, nothing is flushed out to the DOM, so whether an object is created or long-life doesn't matter in this sense.
> mobx needs to walk all your store objects and check for changes, on top of what React does.

I don't think that is quite correct. I think it keeps a mapping of observed properties and which React components rely on them. Then, changing any property becomes a lookup (not a walk) of who is observering, and a `forceRender` on the results. So if no components are observing the property, there's no further computation. Its not "on top of what React does" because it short-circuits it (like useMemo) -- except you don't have to hand-craft any useMemo comparators, it does that for you by tracking which properties you access.