How to pass props through component tree without prop drilling

In React components, it’s very common to share a value or function from a parent component to a child component or deeper in the component tree. In these situations, we have the option to use the props drilling method that shares a value by passing it from one component to its child component, until it reaches the target component.

This method is very cluttered and hard to manage. Fortunately, React provides a hook called useContext as a solution to this problem that allows us to pass a value between any number of components. Let's see how we can use this hook to pass values.

Syntax

The syntax to create a new context object is createContext(). The createContext() function returns an object that has two properties:

  • Provider: It allows the components to subscribe to the context changes.

  • Consumer: It allows the components to consume the context data.

We'll wrap all the components using the shared value with a Provider component. Let's see how this works.

Code example

In this example, we'll pass a userName variable from the App component to its GrandChildren component.

Code explanation

  • Line 1: We import the required modules and functions createContext, useContext, and useState.

  • Line 3: We create a new context using createContext and assign it to the UserContext variable. It's a function that creates a new context object that allows us to share data between components.

  • Lines 7–9: We wrap the ChildComponent with the UserContext.Provider.

  • Line 15: We use the useContext hook to consume the UserContext value and assign it to the name variable.

  • Line 19: We render a simple message using the name value.

  • Line 20: We render the GrandchildComponent.

  • Line 25: We consume the UserContext value using useContext and assign it to the name variable.

  • Line 29: We render a simple message using the name value.

Note: We have used React version 18.0 in this Answer.

Free Resources

Copyright ©2026 Educative, Inc. All rights reserved