Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is State Management?
3.
What are Props?
4.
What are Props Drilling?
5.
Why We Shouldn't Use Prop Drilling?
5.1.
Reasons to Avoid Prop Drilling
6.
Creating React Application
6.1.
Example: Creating a Simple To-Do App
7.
Fixing the Prop Drilling by Using the Context API
7.1.
Example: Using Context API to Manage Global State
8.
Passing Props with Props Drilling
9.
Handling Props Drilling in Complex Applications
10.
Pros of Props Drilling
11.
Cons of Props Drilling
12.
Frequently Asked Questions
12.1.
How Much Prop Drilling is Acceptable?
12.2.
Why is props drilling sometimes considered a problem?
12.3.
How to avoid using props drilling in React?
13.
Conclusion
Last Updated: May 18, 2024
Easy

Props Drilling

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

Welcome to the article, which will upskill your knowledge in React; Props Drilling is a common practice in React. There are different techniques to use instead of props drilling. In this article, we will discuss what props are, props drilling, its pros and cons, and an example demonstrating the situation with or without props drilling.

Before moving forward directly to props drilling, I will recommend you read about state management and react context here.

Props Drilling

What is State Management?

State management in React refers to the process of handling the state of components in a React application. State is a critical concept in React as it allows components to manage and update data over time, enabling interactive and dynamic user interfaces. In React, state is an object that determines how that component renders and behaves.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

What are Props?

In React, Props is a short form of properties that are used to pass the data from one component to another. Props are passed from one component to another as their parameters. Props are passed between components as key-value pairs.

Here’s a short example to understand more:

function Ninja(props) {
  return <h1>Good Morning, {props.name}!</h1>;
}

function App() {
  return (
    <div>
      <Ninja name="Coders" />
      <Ninja name="Ninja" />
    </div>
  );
}

 

In the above example, there is a ‘Ninja’ component which takes a prop called ‘name’, and The ‘App’ component uses using ‘Ninja’ component twice. In the first usage, ‘name’ has a value, Coders. In the second usage, ‘name’ has a value, Ninja.

For the ‘Ninja’ component, Coders and Ninjas are props in each rendering in the ‘App’ component.

Also see,  React Native Reanimated

What are Props Drilling?

In React, Props Drilling is a practice in which a prop or data is passed from one parent component to one or lower children's components, resulting in multiple levels of the component tree. 

For example, consider a simple registration form where the name and email address are props that are essential data for the application. Name and email address pass from higher level component to one lower level component (assume it is A → B and level of A is higher than B). name and email address after reaching B still continues to move to the next lower level component (assume it is B → C and level of B is higher than C). Even though we can move forward to pass this data to lower-level components again, this is where we can say the props drilling has started.

Props Drilling in multilevel components

Now It's very easy to maintain small data, but when the data gets large, props drilling can create many problems in the application. In these situations, we have other techniques, such as react context and redux, that may be used instead of props drilling.

Why We Shouldn't Use Prop Drilling?

Prop drilling refers to the process of passing data from a parent component to deeply nested child components by passing props through intermediate components that do not need the data themselves. While this approach can work for small applications, it becomes problematic as the application grows.

Reasons to Avoid Prop Drilling

  • Maintenance Complexity: Prop drilling makes components tightly coupled because intermediate components have to pass down props that they don't actually use. This can make the code harder to maintain and refactor.
  • Scalability Issues: As the component hierarchy deepens, prop drilling can lead to cumbersome and error-prone code. It can be difficult to track which component needs which props, especially when the data needs to be passed through many layers.
  • Code Readability: Prop drilling can significantly reduce the readability of the code. It becomes harder for developers to understand the data flow, making the codebase more difficult to navigate and understand.
  • Bug-Prone: Passing down props through multiple layers increases the likelihood of introducing bugs. If any component in the middle fails to pass the props correctly, it can break the functionality in deeply nested components.
  • Performance: Prop drilling can lead to unnecessary re-renders of intermediate components that don’t use the props themselves. This can degrade the performance of the application.

Creating React Application

Creating a React application typically involves setting up a new project, developing components, managing state, and implementing the desired functionality. Here’s a step-by-step example of creating a basic React application:

Example: Creating a Simple To-Do App

1. Setting Up the Project: Install Node.js and create a new React project using Create React App:

npx create-react-app my-todo-app cd my-todo-app npm start

2. Creating Components: Create a new file TodoList.js:

import React, { useState } from 'react';
function TodoList() {
 const [todos, setTodos] = useState([]);
 const [inputValue, setInputValue] = useState('');
 const addTodo = () => {
   if (inputValue) {
     setTodos([...todos, inputValue]);
     setInputValue('');
   }
 };
 return (
   <div>
     <h1>My To-Do List</h1>
     <input
       type="text"
       value={inputValue}
       onChange={(e) => setInputValue(e.target.value)}
     />
     <button onClick={addTodo}>Add</button>
     <ul>
       {todos.map((todo, index) => (
         <li key={index}>{todo}</li>
       ))}
     </ul>
   </div>
 );
}
export default TodoList;

3. Using the Component: Update App.js to use the TodoList component:

import React from 'react';
import TodoList from './TodoList';
function App() {
 return (
   <div className="App">
     <TodoList />
   </div>
 );
}
export default App;

4. Running the Application: Start the development server:

npm start

Then open the browser and navigate to http://localhost:3000 to see the To-Do app in action.

Fixing the Prop Drilling by Using the Context API

The Context API in React provides a way to share values between components without having to pass props through every level of the tree. This helps to avoid prop drilling and simplifies state management across deeply nested components.

Example: Using Context API to Manage Global State

1. Creating a Context: Create a new file TodoContext.js:

import React, { createContext, useState } from 'react';
const TodoContext = createContext();
const TodoProvider = ({ children }) => {
 const [todos, setTodos] = useState([]);
 return (
   <TodoContext.Provider value={{ todos, setTodos }}>
     {children}
   </TodoContext.Provider>
 );
};
export { TodoContext, TodoProvider };

2. Providing the Context: Wrap the App component with TodoProvider in index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { TodoProvider } from './TodoContext';
ReactDOM.render(
 <TodoProvider>
   <App />
 </TodoProvider>,
 document.getElementById('root')
);

3. Consuming the Context: Update TodoList.js to use the context:

import React, { useContext, useState } from 'react';
import { TodoContext } from './TodoContext';
function TodoList() {
 const { todos, setTodos } = useContext(TodoContext);
 const [inputValue, setInputValue] = useState('');
 const addTodo = () => {
   if (inputValue) {
     setTodos([...todos, inputValue]);
     setInputValue('');
   }
 };
 return (
   <div>
     <h1>My To-Do List</h1>
     <input
       type="text"
       value={inputValue}
       onChange={(e) => setInputValue(e.target.value)}
     />
     <button onClick={addTodo}>Add</button>
     <ul>
       {todos.map((todo, index) => (
         <li key={index}>{todo}</li>
       ))}
     </ul>
   </div>
 );
}
export default TodoList;

 

By using the Context API, we can manage the state of our application more efficiently, avoiding the issues associated with prop drilling. This makes our code more maintainable, scalable, and easier to understand.

 

Passing Props with Props Drilling

Here’s an example of props drilling that demonstrates a “Good Morning” greeting.

The File Structure for the below code is as follows:

- src/
  - App.js
  - index.js
  - index.html
  - package.json
  - node_modules/
    - (dependencies)

 

In this file structure, file ‘App.js’ has all the below react code.

import React, { useState } from "react";

export function App() {
  const [name, setName] = useState("");
  const handleNameChange = (event) => setName(event.target.value);
  return (
    <div>
      <Greeting name={name} />
      <NameInput onNameChange={handleNameChange} />
    </div>
  );
}

function Greeting(props) {
  return <h1>Good Morning, {props.name}!</h1>;
}

function NameInput(props) {
  return (
    <div>
      <label>Enter your name: </label>
      <input type="text" onChange={props.onNameChange} />
    </div>
  );
}

 

Output:

Before typing any name in the input.

Before typing any name in input

While typing the name in input.

While typing the name in input

The above example demonstrates props drilling by passing props through nested components. The ‘App’ component contains two child components: ‘Greeting’ and ‘NameInput’. The ‘NameInput’ component takes a prop called ‘onNameChange’, which is a callback function passed down from the ‘App’ component to handle changes in the name input field. The ‘Greeting’ component takes a prop called ‘name’, which is a string passed down from the ‘App’ component to customize the greeting. When the user types their name into the input field, the ‘onNameChange’ callback function is called to update the ‘name’ state in the App component, which is then passed down as a prop to the ‘Greeting’ component to render the personalized greeting.

The data passed in the above example is not large enough to make the application complex, but as the data gets complex, the props drilling practice will not be efficient and scalable. Instead of using props drilling, React Context can be used.

Handling Props Drilling in Complex Applications

When an application becomes complex and the data processing becomes deeper, It becomes very difficult for the developer to manage all the states and data. In these scenarios, It’s recommended to use React Context and Redux, which provides an ease to the developers to manage the data and the states between the components.

If a developer wants to handle prop drilling, Here are some steps a developer can follow:

  • Identifying the data and states that are being shared.
     
  • Determining the count of each state will update.
     
  • Estimating the importance of data. So that the unwanted data can be removed.
     
  • Choosing a state management library to handle complex situations such as React Context and Redux.
     
  • Updating the code by adding the chosen specific library and removing the props drilling that is dealing with the complex data.

Refer to know  about, React Native Paper, React devtools

Pros of Props Drilling

  • Props are easy to pass from one component to another.
     
  • Testing in the application becomes convenient as it explicitly shows which props are passing to which components.
     
  • Props Drilling also makes it easy to trace the path in which the props are passed from a higher level to lower level components.
     
  • Props Drilling can be better than react context and global state in terms of performance. 
     
  • Props Drilling avoids unneeded re-renders and minimizes the updation of a number of components.

Cons of Props Drilling

  • As the data in the props increase, It can be difficult to trace the path.
     
  • Naming collisions can occur if some components have a prop with the same name.
     
  • Props Drilling is very risky for the application, with props passing in deeply nested components.
     
  • Maintaining the props can be difficult when the component tree is too deep or complex.

Frequently Asked Questions

How Much Prop Drilling is Acceptable?

A minimal amount of prop drilling is acceptable, typically limited to one or two levels. Beyond that, consider using context or state management libraries to simplify the code.

Why is props drilling sometimes considered a problem?

When the data in props is not large, or we can say it's easy to maintain, props drilling is the best practice as the implementation is easy, but as the data gets complex, the props drilling practice will not be efficient and scalable.

How to avoid using props drilling in React?

React Context can be ContextAPI, a react hook that allows sharing the data between components without passing the props to multiple levels of nested components. React Context can also be used if the data is too large to maintain, whereas while using props drilling, data can not maintain.

Conclusion

In this article, we discussed what props drilling is and how props drilling actually works. Using props drilling, we also learned how to pass the props to multiple nested components. Now as we know, what are the advantages and limitations of props drilling? React Developers should also use the React Context as the applications are getting complex. I recommend everyone to read about React Context Here.

Do check out The Interview Guide for Product Based Companies, as well as some of the Popular Interview Problems from Top companies like AmazonAdobeGoogleUberMicrosoft, etc., on Coding Ninjas Studio.

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMS, and System Design, etc. as well as some Contests, Test SeriesInterview Bundles, and some Interview Experiences curated by top Industry Experts only on Coding Ninjas Studio.

Live masterclass