2

̶R̶e̶a̶c̶t̶ VUE Context Provider Pattern With Custom Hooks

 2 years ago
source link: https://dzone.com/articles/react-vue-context-provider-pattern-with-custom-hoo
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

The Problem

Vue has lots of tools out of the box that makes our life easier, e.g Vuex and Vue-router. But, it still relies too much on magical connections, which makes code hard to understand. In order to help IDE and future me with code readability, I've started to think about hooks and patterns that come along with them.

The Code

In this sandbox, you can find React's Context Provider Pattern applied to Vue's Composition API provide and inject methods.

The Conclusion

Vue has a very powerful plugin Vuex for state management. But, often, you are unable to share the state in a simpler way or to multiply the same state functionality. Therefore, you have two standard solutions, props drilling and provide/inject. Drilling is good as long it's no deeper than 3 levels. But provide/inject, in their raw form, are relying too much on magic for my taste.

15353199-context.jpg

An important note: This pattern is not intended to replace Vuex, but to complement it. The rule of thumb here is to have the Vuex store for the global state and the Context state for a group of components. For E.g, Vuex is used to bring userData inside the Header Component, closer to the User Menu. And the User Menu Root Component is passing data from Store to its atomic components via Context Provider pattern using under the hood provide and inject.

This gives us Decoupled Components that are easy to run and test separately with Storybook, Mocks, Jest Snapshot, etc.

The Takeaway

If Composition API borrows so much from React already, why not keep that in mind and make Vue more lovable by combining the best of both worlds? Don't be afraid to experiment by mixing features and patterns for the greater good.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK