Listing 17-1: Using Prop Drilling
Here's the story that was passed down to the Grandson component: test
const Grandpa = (props) => {
return (<Dad story = {props.story} />);
}
const Dad = (props) => {
return (<Son story = {props.story} />);
}
const Son = (props) => {
return (<Grandson story = {props.story} />);
}
const Grandson = (props) => {
return (<p>Here's the story that was passed down to the Grandson component: {props.story}</p>);
}
export default Grandpa;
Prop Drilling
Data in React is passed down from parent components to child components using props. Often, it's necessary to pass certain data through multiple layers of components to get that data to the component where it's needed. This is what's referred to as 'prop drilling.'
Prop drilling is a normal pattern and best practice in React. There are times, however, when 'global' data, such as user preferences or theming information must be passed to many different component and through multiple layers. If prop drilling becomes hard to keep track of or otherwise causes problems, it can be useful to use a technique such as React Context or Composition to reduce or eliminate it.
Download the examples, report issues, and ask/answer questions in the discussion area by visiting the book's github page. All of the code for the book is also available on codesandbox.io for you to play around with.
ReactJS Foundations is published by John Wiley and Sons, Inc and is available in paperback and eBook.