What is Prop drilling? and how to solve it using Context API
2021-04-23
React interview cheatsheet series
As we know, the props are the data we pass -or can access- from the top-level components to its child components. And, also we know that React data flow is unidirectional.
Prop drilling, also know as threading, is the process where the devs pass the props down to an specific child component, but in between, other components, between the origin and the destiny, get the props just to pass it down the chain. So props drilling issue is when passing this data from the parent component (A) to a children component (Z), but in the middle this data pass through many components in t between A and Z that doesn't need that data (props) excepts to communicate A and Z.
Props drilling is not a problem at all if we have a couple or three levels, but imagine if we have dozens of levels... That's the problem.
There is a good video explaining this here.
To avoid prop drilling, in other words, passing props through intermediate elements, we have some solutions:
- React Context API.
- Composition
- Render props
- HOC (High Order Components)
- Redux or MobX
1. Avoid Props Drilling with React Context API
Context is designed to share data that can be considered “global” for a tree of React components, such as the current user, theme, or language.
Context is primarily used when some data needs to be accessible by many components at different nesting levels. So, if you only want to avoid passing some props through many levels, component composition is often a simpler solution than context.
Context API was created as an answer to prop drilling, and an easier alternative to Redux.
There is a great Toptal.com article abut this, I invite to read it, this great an eloquent image is given from there:
See an interesting article at https://www.toptal.com/react/react-context-api
const MyContext = React.createContext(defaultValue);
Creates a Context object. When React renders a component that subscribes to this Context object it will read the current context value from the closest matching Provider above it in the tree.
The argument is only used when a component does not have a matching Provider above it in the tree.
<MyContext.Provider value={ value }>
Every Context object comes with a Provider React component that allows consuming components to subscribe to context changes.
The Provider component accepts a value prop to be passed to consuming components that are descendants of this Provider. One Provider can be connected to many consumers.
All consumers that are descendants of a Provider will re-render whenever the Provider’s value prop changes.
1import React, { Component } from "https://cdn.skypack.dev/react"; 2 3const AppContext = React.createContext(); 4 5class AppProvider extends Component { 6 state = { 7 teamMembers: { 8 player001: { name: 'Joaquin', position: 'Forward', number: 7 }, 9 player002: { name: 'canales', position: 'Midfielder', number: 10 } 10 } 11 }; 12 13 render() { 14 return ( 15 <AppContext.Provider 16 value={{ 17 players: this.state.teamMembers 18 }} 19 > 20 {this.props.children} 21 </AppContext.Provider> 22 ); 23 } 24}; 25 26const TeamList = () => ( 27 <div> 28 <h2>Real Betis Balompié:</h2> 29 <Players /> 30 </div> 31); 32 33const Player = props => ( 34 <tr> 35 <td>{props.number}</td> 36 <td>{props.name}</td> 37 <td>{props.position}</td> 38 </tr> 39); 40 41const Players = () => ( 42 <AppContext.Consumer> 43 {context => ( 44 <div> 45 <h4>Players:</h4> 46 <table> 47 <tr> 48 <th>Number</th> 49 <th>Name</th> 50 <th>Positon</th> 51 </tr> 52 53 {Object.keys(context.players).map(key => { 54 return <Player key={context.players[key]} 55 number={context.players[key].number} 56 name={context.players[key].name} 57 position={context.players[key].position} 58 /> 59 })} 60 </table> 61 </div> 62 )} 63 </AppContext.Consumer> 64); 65 66class App extends Component { 67 render() { 68 return ( 69 <AppProvider> 70 <div> 71 <TeamList /> 72 </div> 73 </AppProvider> 74 ); 75 } 76}; 77 78ReactDOM.render( 79 <App />, 80 document.getElementById('root') 81);
See the code working at codepen
2. Composition
Composition is an easy but powerful tool to reuse code and share props between components.
Composition uses the children prop to pass the all the elements, see:
1const AlertBox = (props) => ( 2 <div className={'alertbox alertbox__' + props.type}> 3 {props.children} // will renders: <p>This is just a dummy message!</p> 4 </div> 5); 6 7const loreIpsum = () => ( 8 <AlertBox type="error"> 9 <p>This is just a dummy message!</p> 10 </AlertBox> 11); 12
About composition and props drilling in React, there is an excellent article in Medium written by my old mate Bolu, Composition: An Alternative to Props Drilling in React, better reading it, it's so clear.
See also: Props Drilling In React.Js