Is it ok to use a global store to persist component state between mounts?
Sometimes I want to be able to keep some component state between mounts. Partially filled form state is a good example. Is it ok to use a global store for this? Is there a better way?
17 Replies
If you can guarantee that there will only ever be one instance of that component, it could be fine. But generally this assumption has burnt me in the past. What I do now is just hoist that state to closest stable parent and maybe put it in a context to avoid prop drilling.
@deluksic Can you explain how using a global store in this way could cause a problem?
If for some reason you want to render that component elsewhere and you did not expect the state to be transferred there as well. Resetting that state can sometimes be too important to leave to chance. Second reason could be usage of SolidStart where globals just dont work correctly. Third reason is a bit niche: its harder to test in storybook because you want to render many instances of the same component and sharing state between them is usually not expected.
If for some reason you want to render that component elsewhere and you did not expect the state to be transferred there as well.You mean, if I had two instances of a component which uses a global store, the problem would be that they would both share the same store instead of each having a separate store?
Resetting that state can sometimes be too important to leave to chance.I don't understand what you mean by this. How does using a global store mean the same as or have as a consequence that resetting that state would be left to chance?
What about reloading? Does it must support reloading?
What do you mean? A page refresh?
Yeah
No
Then using a global store should probably work
If it did though, wouldn't that just be a matter of saving to localStorage/database when state changed and restoring it on mount if it exists?
Pretty much.
So what would the problem be with regards to global stores?
I mean, would it be a problem to use a global store if I also wanted to persist state after a page refresh?
Only localstorage survives page refresh
oh, yeah, I understand that
thanks!
keep it simple, store the id of the form as key for example. Just be mindful of the id to avoid conflict.
If you are doing SSR in the future, module globals involved during SSR are a no-go as those are shared across concurrent requests on the server.
What I meant by leaving reset to chance is that you rely on developers (yourself) to remember to reset some state, i.e. it is not done automatically on re-render. Picture a patient management system where you forget to remove details from the previous patient on navigation.