useContext React Hook

useContext React Hook

Props is a special keyword in React that simply stands for properties and is used for passing data from one component to another, one thing to note is that data with props are passed in one direction, from parents to child. The use of props in React is very cool but at the same time, it can quickly sour especially when you have to pass data through deeply nested components that is what we call prop drilling. Let me create a scenario, imagine you work in a company that has a four-storey building with no functional elevator and you have to use the staircase every time you want to see a friend who works on the ground floor since you work on the fourth floor, that is crazy right? That is what prop drilling is like. To make things easier and more efficient the useContext React hook was developed.

Context

ContextAPI in React is an alternative way of passing data through the component tree without the need to prop drill. ContextAPI is particularly useful when dealing with data that is considered “global” or needs to be accessible by many components within the application.

How to use the useContext React Hook

There are three steps to remember when you want to use the useContext React Hook and they are: creating the context, providing the context, and consuming the context.Let us quickly move to the first step.

Step 1: Creating the Context

The first thing is to import createContext from React like in the code snippet below;

import {createContext } from "react";

After importing the createContext from React the next thing we will do is to define.

import {createContext } from "react";

const Context = createContext();

It is important to note that the createContext function accepts only one optional argument. After importing and defining the createContext, we will move to the next step. One thing to note is that this userContext is now divided into three parts:
Provider: The provider gives all child components access to the value: One thing to note is that the provider can be put anywhere in the component tree but it is common to place it at the top.

Consumer: These are all the components that read the value passed into the provider in other words consumers are components that read the context.

Value: This is the data we want to make available, usually, it contains one or more states and functions. It will make more sense in the next step, just stay with me.

Step 2: Providing the Context

This next step is quite straightforward like the first step. The first thing you want to do is identify the parent component among your component tree. In some component trees, it can be the App.js component while in some it can be the Main.js. After identifying the parent component, we will wrap the parent component markup with the Context provider to have all child components subscribe to Context changes. Let us jump straight into the code:

import {createContext } from "react";

const Context = createContext();

function App() {
  const [name, setName] = useState("Jesse Hall");
  return (
    <Context.Provider value={{name}}>
      <Childcomponent1 />
      <Childcomponent2 />
      <Childcomponent3 />
    </Context.Provider>
  );
}

From the code above, we can see that after passing the values we want through the provider all the child components wrapped will be able to access these values through the useContext Hook. Another thing to note is that the value can be more than one and can be anything ranging from states, functions, objects, or even arrays.

Step 3: Consuming the Context

To use the Context in a child component, we need to consume the context and we can consume the context using the useContext Hook. The useContext hooks accept a context object (the value when we imported createContext from React).It is also important to note that a component calling the useContext hook will always re-render whenever the context value changes.

import { useState, createContext, useContext } from "react";
const Context = createContext();

function App() {
  const [name, setName] = useState("Jesse Hall");
  const [age, setAge] = useState(44);

  function ageHandler () {
  setAge(age + 1) 
  }
  return (
    <Context.Provider value={{value1:name,value2:age, 
     value3:ageHandler}}>
      <Childcomponent1 />
      <Childcomponent2 />
      <Childcomponent3 />
    </Context.Provider>
  );
}

function Childcomponent1 () {
const {value1, value2, value3} = useContext(Context)
return (
 <section>
  <h1>My name is {value1}</h1>
  <p>I am {value2} years old</p>
 </section>
)
}

In this code snippet, I added more things to the code like a new state and a function into the provider. In one of the child components, I called the useContext react hook and consumed the context we had earlier. To make my work easier and prevent bugs, I destructured my values and used them directly. However, it is important to note that most developers use custom hooks whenever they work with the useContext hook and I subscribe to it.

Conclusion

The useContext Hook is a fantastic hook to use, which might not be beginner-friendly. However, if you follow the three steps I outlined in my article then you will not face any challenges. One important thing to note is that useContext is best used when you need to share data across multiple components at different levels of the component tree, especially when passing props becomes cumbersome and difficult to manage.