Advantages of Crafting Custom Context Hooks for Consumption
Why you should create a hook to consume context
2 min readAug 30, 2023
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:
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?
Let’s jot down the problems:
- In every component we have to carry around the
ThemeContext
we have to import it along withuseContext
- In every component we have to call
useContext
hook withThemeContext
. - 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 orThemeContext
.
What is the solution?
As usual, the solution lies in a custom hook. ⚓️
- Make sure there exists a separate component for you Context.
- create a custom
hook
which will be responsible for callinguseContext
,for type guards and returning the context.
After using this hook, our components will look like this: