Context Module Pattern in React
Do you see the beast? context + hooks === 🦁
Using context and hooks together gives birth to Context Module Pattern, the magnificent beast🦁.
Let’s start by creating the context:
Here I prefer to split my context into state and dispatch, this enables me to consume only what my component needs. To allow our components to consume these contexts we must attach their provider in the ancestral component tree. I prefer to create a wrapper component that provides these context as:
Now let's create custom hooks to consume these context values:
Note that we never export context itself as we will consume context by using our custom hooks. Now that is in place we can move to implement state modifier helper functions which in combination with dispatch helps to modify state.
Now all that is in place it is time we conclude our context module. Now let’s see how to use it.
Note that how easy it is to use context in code, we are leveraging hooks and helper functions to abstract complexity and simplify our code.
Context module pattern — a beautiful magnificent beast 🦁.
To see a more complex example follow this link code sandbox