Context Module Pattern in React

Aniket Jha
1 min readFeb 22, 2021

--

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:

Create Context [context.js]

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:

Create Context Provider [context.js]

Now let's create custom hooks to consume these context values:

Context hooks [context.js]

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.

create state modifier helpers [helpers.js]

Now all that is in place it is time we conclude our context module. Now let’s see how to use it.

Using Context Module Pattern [App.js]

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

--

--