What is Props drilling in React?

devquora
devquora

Posted On: Jul 17, 2023

 

In React, props are a way for components to receive data from their parent components. Props drilling, also known as props tunneling, refers to the practice of passing props from a top-level component down through several layers of child components, even if those child components do not directly use the props.

Here is an example of props drilling in action:

// Top-level component
function App(props) {
  return   < MyForm {...props} />;;
}

// Intermediate component
function MyForm(props) {
  return  < MyInput {...props} />;;
}

// Leaf component
function MyInput(props) {
  return <input value="{props.value}" type="text" />;
}


In this example, the App component passes its props down to the MyForm component, which in turn passes them down to the MyInput component. The MyInput component is the only one that actually uses the value and onChange props, but all of the other components in the hierarchy also receive and pass along the props.

Props drilling can become cumbersome when a component deep in the hierarchy needs to use props from a higher-level component. It can also make the code harder to understand and maintain, as it is not immediately clear where the props are being used. To avoid these issues, it is generally recommended to use techniques like context or the React Router to pass data between components that are not directly related in the hierarchy.

    Please Login or Register to leave a response.

    Related Articles