Today’s Offer Enroll today and get access to premium content.
App Store Google Play
Advanced

What is prop drilling in React, and how can it be avoided?

Prop drilling refers to the process of passing data from a parent component down to deeply nested child components via props. While this is a common practice in React, it can lead to cumbersome and hard-to-maintain code.

To avoid prop drilling:

  1. Context API: Use the Context API to provide data at a higher level and consume it in any child component without prop drilling.
  2. State Management Libraries: Utilize libraries like Redux or MobX for managing app-wide state.
  3. Component Composition: Restructure components to reduce the need for deeply nested props.

Example using Context API:

const MyContext = React.createContext(); const Parent = () => { return <MyContext.Provider value={'Hello'}><Child /></MyContext.Provider>; }; const Child = () => { const value = useContext(MyContext); return <p>{value}</p>; };