DEV Community

Cover image for The Secret Life of Context API
Sobhan Dash
Sobhan Dash

Posted on • Updated on

The Secret Life of Context API

Before getting to know about the awesome feature of Context API we first need to know why we need this hook. Much like useReducer hook, it is an advanced concept of React.

Prop Drilling

There is a concept called Prop Drilling. When we build any small-scale app we often don't encounter it. But once we start developing a moderately complex web app the state management gets really tedious.

Recently I'm working on a personal project, at first the state management was not that hard but once I started making different new components and pages it got slightly hard to keep track of it. Although I knew about Context API and another concept called Redux. I didn't plan my project well enough to use them and had a difficult time with it.
Why did say that? Well, what I basically had to do was prop drill.

When a function or a state is declared in the top level of a component tree and is passed down to the bottom of the tree with at least some components between the declared component and required components then it is called Prop Drilling.
Prop Drilling

What I mean is let's say you have a state called userpost and a function setUserPost and it has been declared in the Index Page where you have another component called Feed. Now this Feed component has another component inside it called as FeedForm.

You need the state userpost in the FeedForm, which has been declared in the Index Page. How do we get it? Well first we need to send it to the Feed component then we send it to the FeedForm component.

Because this is a relatively small gap you might not notice it. But think of a large web app which have multiple different components. I assume you get the picture. The components in between the declared and required components don't need the state, still, they have to get access to the prop in order to send it to the next component.
This is where concepts like Context API and Redux come in.

Context API or useContext Hook

So, as I said already this hook helps us manage states with much more ease. Although the initial declaration and the way to invoke it might extend to 3-4 lines of extra code, ultimately it solves the problem of prop drilling.

Initially, we have to import the createContext hook from react.
After that, we have access to a component called Provider. It's like a distributor which is wrapped around the root component often times it's the main App or Routing.
It's wrapped using the variableName.Provider.
Example of how to use ContextAPI:

import {​ ​createContext,​ ​useReducer​ ​}​ ​from​ ​"react"; 
import​ ​RouteConfig​ ​from​ ​"./Router";
import​ ​{​ ​reducer,​ ​initialState​ ​}​ ​from​ ​"./reducers/userReducer"; 
export​ ​const​ ​UserContext​ ​=​ ​createContext(); 

const​ ​App​ ​=​ ​()​ ​=>​ ​{ 
 ​  ​const​ ​[state,​ ​dispatch]​ ​=​ ​useReducer(reducer,​ ​initialState); 
 ​  ​return​ ​( 
 ​    ​<UserContext.Provider​ ​value={{​ state,​ dispatch ​}}> 
 ​      ​<RouteConfig​ ​UserContext={UserContext}​ ​/> 
 ​    ​</UserContext.Provider> 
 ​  ​); 

 export​ ​default​ ​App;
Enter fullscreen mode Exit fullscreen mode

Once the root component is wrapped we can easily import it into other components. We just have to import useContext Hook and then call for the state and dispatch with it.

//Inside A different component
import​ ​React,​ ​{​ ​useContext,​ ​useEffect​ ​}​ ​from​ ​"react";
import​ ​{​ ​UserContext​ ​}​ ​from​ ​"../../App";
const Example =()=>{
  const​ ​{​ state,​ dispatch ​}​ ​=​ ​useContext(UserContext);
return (
Enter fullscreen mode Exit fullscreen mode

From the above code, we can use the state and dispatch however we like and visualize it as being several levels deep inside a DOM Tree.

1- In the example, I'm not populating the state so you won't see any result here.
2- I've also used another hook useReducer for better state management in the example. Check out about it in the previous installment of the series.

Do let me know your thoughts and follow my Twitter and LinkedIn.

Top comments (0)