Code Skiller logoCB Logo
Logo LearnLearnLogo PracticePracticeLogo HireHireLogo IDEIDE

Prop drilling in React JS

User image

Published by

sanya sanya

Published at: 28th Jul, 2023
1.385 mins read

Prop drilling is a term used in React JS to describe the process of passing props (properties) from a parent component to its child components, and potentially further down the component tree. It occurs when intermediate components in the hierarchy don't need the props themselves but are required to pass them down to their children.

Prop drilling typically happens when you have a deeply nested component structure, and data or functionality needs to be passed from a higher-level component to a lower-level component.

The example to illustrate prop drilling in React JS is mentioned below -

 import React from 'react';

 // Top-level component
 const App = () => {
   const data = 'Some data';
 
   return (
          <div>
       <ParentComponent data={data} />
     </div>
   );
 };
 
 // Intermediate component
 const ParentComponent = ({ data }) => {
   return (
     <div>
       <ChildComponent data={data} />
     </div>
   );
 };

 // Lowest-level component
 const ChildComponent = ({ data }) => {
   return <div>{data}</div>;
 };

 export default App;

In this example, the data prop is passed from the top-level App component to the ParentComponent, which in turn passes it down to the ChildComponent. The ParentComponent doesn't actually use the data prop itself but simply forwards it to its child component. This is prop drilling.



Prop drilling can become cumbersome and reduce code maintainability when the component tree is large and deeply nested. It requires passing the same prop through multiple levels of components, even if the intermediate components don't use the prop directly. It can also make refactoring or modifying the component structure more challenging, as any changes to the prop flow may require updating multiple components.

Library

WEB DEVELOPMENT

Basic

Frontend

Express JS

React

Hello World in ReactJS

Rendering Elements

States and Lifecycles in React JS

Handling Events in React JS

Introduction to JSX

Components and Props in React JS

Conditional Rendering

Lists and Keys in React JS

Introduction to Redux

Types of components (class vs functional)

Using the useEffect hook

Building custom hooks in React JS

Context API in React JS

Forms in React JS

Lifting State Up in React JS

Composition vs Inheritance

Prop drilling in React JS

Introduction to Hooks

Using the useState hook

UseMemo vs useCallback

Backend

Interview Questions

FAANG QUESTIONS