Avoiding Prop Drilling with usecontext

1 min read
Cover Image for Avoiding Prop Drilling with usecontext

Prop drilling in React refers to the process of passing data from a parent component to deeply nested child components via props, even if intermediate components do not need the data. This can make the code harder to maintain and scale.

So, instead of passing props manually, we can use React.createContext() to share data across components.

how to use useContext

1) Defining the context

import { createContext } from "react";
export const GlobalContext = createContext(null);

2) Create a context provider

We will use a provider to wrap the component that need access to the shared state.

import LevelOne from './components/One'
import { GlobalContext } from './context'

function App() {
  const message = "This text comes from context, skipping prop drilling!";
  return (
    <GlobalContext.Provider value={message}>
      <LevelOne />
    </GlobalContext.Provider>
  );
};

export default App

3) Use the context in the child component

In this case it was used on third level deep component

import React, { useContext } from 'react';
import { GlobalContext } from '../context';

export default function LevelTree() {
  const message = useContext(GlobalContext);
  return <p>{message}</p>;
};

You're all set!

So with useContext, we can directly access shared state in any component without doing prop drilling.

Codepen