Advantages of Crafting Custom Context Hooks for Consumption

Why you should create a hook to consume context

Photo by Grant Durr on Unsplash

In React, we have an awesome way of passing props and setter function to deeply nested child components without passing them individually in subsequent components. We do so by using Provider-Context concept.

This is how it works:

Creation and Consumption flow of Provider Context

So what’s the problem in it?

Suppose we have to use the same context in multiple components. The this is how our components will look like.

Have you spotted the problem?

Have you spotted the problem?

Let’s jot down the problems:

  1. In every component we have to carry around the ThemeContext we have to import it along with useContext
  2. In every component we have to call useContext hook with ThemeContext.
  3. If we are using TypeScript, then we have add additional check to ensure we are getting data in context, because initially we have used null to initialise or ThemeContext .

What is the solution?

As usual, the solution lies in a custom hook. ⚓️

  1. Make sure there exists a separate component for you Context.
  2. create a custom hook which will be responsible for calling useContext ,for type guards and returning the context.
useThemeContext() will solve the problem

After using this hook, our components will look like this:

--

--

राहुल मिश्रा
राहुल मिश्रा

No responses yet