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, anduseState.Line 3: We create a new context using
createContextand assign it to theUserContextvariable. It's a function that creates a new context object that allows us to share data between components.Lines 7–9: We wrap the
ChildComponentwith theUserContext.Provider.Line 15: We use the
useContexthook to consume theUserContextvalue and assign it to thenamevariable.Line 19: We render a simple message using the
namevalue.Line 20: We render the
GrandchildComponent.Line 25: We consume the
UserContextvalue usinguseContextand assign it to thenamevariable.Line 29: We render a simple message using the
namevalue.
Note: We have used React version 18.0 in this Answer.
Free Resources