DEV Community

Discussion on: The Correct Way to Use Stores in SvelteKit

Collapse
 
jrmoynihan profile image
jrmoynihan • Edited

Your point about not needing global state when local will do is great.

That being sad, your point in #2 has some exceptions. Isolated components might need to make use of certain stores, like tweened and spring because they already provide specific behaviors out of the box.

I also like the idea to use stores + contexts, but I found this implementation a little hard to follow. Part of it is probably the nomenclature you used in the post. These aren't "hooks", at least in Svelte's definition of them, even though they provide similar functionality to React hooks. The "useWritable" semantics also feel weird -- if I wanted to use writable(), I'd just import it! What does "use" tell you about what the function does?

As a comparison, I wrote a similar type of convenience function for stores + contexts a while back with some more explicit typing, even for the generics, but I also stuck with the "get/set" naming convention Svelte uses internally for contexts. I think this makes it much more clear to the end-user what is actually being done here. You could still make a getDarkMode() function if you were doing that context lookup a lot and wanted a quick alias for getWritableContext('dark').

One of the problems with context that Rich brings up in the tutorial, is using unique keys within a context tree. I don't think your implementation can deal with that as-written. Symbol can solve that, as he points out.

Lastly, I'm curious why you chose to put the getContext() and setContext() within the same function, useSharedStore? That feels a little risky to me. Isn't it important to know that a context a child component is trying to get wasn't set above in its parent tree? The child component shouldn't be doing the setting here if the provided key fails the if(hasContext(name)) check!

I don't always get the single-responsibility principle correct in my own code either, but this seems like it would be substantially improved just by being more explicit, and splitting up the functionality.

Collapse
 
jdgamble555 profile image
Jonathan Gamble

What is tweened and sprint? I think I agree there are exceptions, but generally people could avoid stores for reactive statements.