Sharing State - Venue Component
Read about how to share state in the venue component this lesson.
We'll cover the following
Lifting state up and passing state down
Hooks and useState
work very cleanly when the state is completely encapsulated inside one component, but often components have to share state. Sometimes state is shared among just one subtree of DOM elements on the page, but sometimes state is shared across a page. I’ll talk more about this in Managing State in React, but I did want to cover the simplest version of one common scenario, where state is shared among parent and child components.
In this React pattern, when state is shared between components, and there is a common parent to all the components that need that state, the state is typically owned by the common parent. The parent sends the raw values down to the child components as props and typically also sends a function that the child components should call to change the parent state. When the parent state changes, the parent component re-renders, causing the child components to re-render with new prop values. This pattern is called “lifting state up” and “passing state down.”
As an example, let’s imagine we can use a pull-down menu to determine the number of seats we want to purchase at a time, and clicking on a seat selects that total number of seats to the right of the seat clicked on. If that number of seats is not available to the right, then the seat is marked invalid and clicking it has no effect.
This feature adds one new piece of state: the number of seats being purchased via the pull-down menu. It also requires that Seat
components need to know something about the seats to their right in order to know their status. In the first case, the state for the number of seats being purchased should be owned by the common parent of all the components that use it, which here would be Venue
.
Similarly, we need to lift the state of an individual seat up to the Row
so that the row can determine which seats are valid for purchase given the number of seats requested. When the value in the pull-down menu is changed, that state change needs to trigger a redraw of each row because the set of valid seats changes. When a Seat
is clicked on, the Row
needs to update the status of the nearby seats.
Implementing the pattern
Here’s what that looks like in code. Let’s start from the top with the new version of the Venue
component:
Get hands-on with 1200+ tech skills courses.