Search⌘ K

The useContext Hook

Explore how to use the useContext Hook in React to simplify data sharing across components without prop drilling. Learn to create and consume context for themes, languages, and user data. This lesson helps you manage global state effectively to build cleaner, maintainable React applications.

In React, managing shared data between components can be challenging as the application grows. Passing props through multiple levels (a process known as prop drilling) can quickly make our code verbose and difficult to maintain.

Prop drilling

Prop drilling is a situation in React where data (props) is passed from a parent component to deeply nested child components through intermediate components that don’t need the data. It occurs when a parent component needs to provide data or functions to a child that is several layers deep in the component tree, requiring each intermediate component to drill or forward the props down the hierarchy.

  • Line 2: The user object (data) originates in the App component.

  • Lines 4, 8, and 12: To reach the GrandChild component, the user prop is passed through ParentChild, and finally to GrandChild.

The Parent and Child components don’t need the user data, but they still have to receive and forward it as props.

How to avoid prop drilling

React provides features (such as the Context API and the useContext Hook) to address ...