What is useContext?

Prerequisites

This blog assumes you're already familiar with React and React Hooks.

Why should you use useContext?

To avoid the pain of prop drilling, we use the useContext hook. as you may know. Prop drilling is the process of transferring props from to each child component of a component tree.

prop.png

It adds complexity to the code and lengthens it. If we wish to transfer data to ChildC, we must first pass it to ChildA, then to ChildB, and finally to ChildC. Even ChildA and childB do not require that information. To overcome this problem we use useContext hook.

let's get started.

What is useContext.

Context allows you to send data or state to each component in a component tree without having to pass props to each child component.

Don't worry we will understand this with an example.

Create context

To construct a context that react provides, we'll use createContext. To create context, we must first import it from react.

import { createContext } from 'react'
const ThemeContext = createContext(null)

Provide Context

We'll wrap our parent node in a context provider so that value is passed along to all child components.

<ThemeContext.Provider  value={{ theme: "light" }}>
      <App />
</ThemeContext.Provider>

Consume Context

React provides useContext to use the context. We will use it to consume data.

import { useContext } from "react";
const {theme} =  useContext(ThemeContext)

State in context

What will we do if we wish to pass the state on to our children? we will pass state in value prop as we did before. look at this example.

import { createContext, useContext, useState } from "react";

const ThemeContext = createContext({ theme: "light" });

const useTheme = () => useContext(ThemeContext);

const ThemeProvider = ({ children }) => {
  const [theme, setTheme] = useState("light");

  const changeTheme = () => {
    setTheme((theme) => (theme === "light" ? "dark" : "light"));
  };

  return (
    <ThemeContext.Provider value={{ theme, setTheme, changeTheme }}>
      {children}
    </ThemeContext.Provider>
  );
};

export { ThemeProvider, useTheme };

We've extracted contextProvider to a separate file and passed the prop children. You can read about children prop here. In addition, if you are not aware, I am constructing a custom hook. Click here to read it.

Now we can utilise it whenever and wherever we choose.

const { changeTheme } = useTheme();

Closure

Thank you for reading till the end. Let me know in the comments if you like the blog or if you have any suggestions!