Is this a good practice? #85
-
Hello guys, I'm trying to simplify things and have a small boilerplate for my stores, I'm wondering if this is a good or bad practice? I'm coding my stores this way so I just need to copy/paste the same file and replace the props whenever I need a new store use-ui-store.js
Then I use it like this
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hi @joelbqz , So, the only issue that I see here is that you would be creating multiple subscriptions which will be individually listening on each of those keys. This isn't generally the most effective way to do things- its better to define your The main issue would be if React will batch those updates (if you are listening to, and change more than one value at the same time). Currently it might not be so, and you might have to wrap your store updates in something like
Though this is an unstable API and might change in React in the future. React also does do some automatic batching, but you would have to test that out (maybe with some Another option which just dawned on me, is you could do something like this: function useUiState(keys: string[]) {
const values = UIStore.useState(s => keys.map(k => s[k]));
const setters = keys.map(k => (newValue) => UIStore.update(s => {
s[k] = newValue
}));
return [values, setters];
} So that would return something you can use like so: const [[isDarkMode, isSmall], [setDarkMode, setIsSmall]] = useUIState(["isDarkMode", "isSmall"]); But this is also not amazing UX. You could also rather map those values and setters to separate objects with the actual keys as keys of the object for a nicer UX, but more complicated types if you're using typescript. |
Beta Was this translation helpful? Give feedback.
Hi @joelbqz ,
So, the only issue that I see here is that you would be creating multiple subscriptions which will be individually listening on each of those keys. This isn't generally the most effective way to do things- its better to define your
Store.useState()
listener once for all the required state.The main issue would be if React will batch those updates (if you are listening to, and change more than one value at the same time). Currently it might not be so, and you might have to wrap your store updates in something like
Though this is an unstable API and might change in React in the future. React also does do some aut…