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

Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 4 years ago

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.

egghead
egghead
~ 32 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today