Identify the need to elevate state to a parent component in React

Share this video with your friends

Social Share Links

Send Tweet

In this lesson, we look at our "component breakdown diagram" again. It becomes apparent that the state for the input field search value needs to also be available for the NamePicker component. We therefore elevate that piece of state to their common parent (App.js), and pass it down to both components via props.

Simon Vrachliotis: [0:00] Let's look at our final App again. It's pretty obvious that the state value we are holding in the Search component needs to also be available in the NamePicker component. One way to share a piece of state across multiple components is to elevate that state to a common parent component.

[0:16] In our case, we're going to elevate the search value state to the App.js component which is the common parent for both Search and NamePicker. Let's import useState in our App.js file and move the searchValue state definition from Search to App.

[0:32] The App component will now be responsible to keep track of the Search field value and we can pass both searchValue and setSearchValue to our search component through props. NamePicker only cares about the searchValue, it will never update the value itself so we don't pass setSearchValue here.

[0:51] In the Search component we can now remove the useState definition as well as the import. Instead, we obtain these values from the props.

[1:02] Let's also receive the searchValue prop in NamePicker, and we'll deal with that next.