Introduction to Managing State in React
Get an introduction to managing state in React.
We'll cover the following
Managing state in React
As we’ve built up the React page in our app, we’ve been passing properties and handlers up and down the DOM tree to allow our data to be shared between components. This is somewhat complicated and error-prone. Using a global data store will keep us from having to do all this property passing—all we’ll need to do is make sure each component subscribes to the global store and also sends actions to it.
React comes with built-in features to support this kind of global data sharing, and it also contains hook methods that we can use in our functional components to access this data.
To see how global data can help, let’s add a new feature to our concert page that builds up a price subtotal based on the number of tickets the user has on hold and also allows the user to clear all tickets from the subtotal section. As currently implemented, this would involve even more passing of data up and down the DOM tree, but we can use contexts and reducers to centralize the data.
Using context to share state in React
The first feature of React that will help us is called a context, which is accessible in our components with a hook method called useContext
. With a context, we surround our code with a special JSX component called a context provider, which gives all the components inside that provider access to the data in the context.
We’ll also use a hook called useReducer
, which takes a function that implements the reducer pattern as we’ve already seen it in the Refactoring to the Reducer Pattern lesson and provide some ease of use for accessing the reducer.
Moving our code to use a context and a reducer ends up being a fairly significant refactoring of our React code, so let’s talk about what we need to do. Our existing data model sets a bunch of data at the Venue level, which is passed down to each Row.
Each Row maintains a list of the statuses of its component seats and passes that information to each Seat. The Seat status is held in the Row, because the status depends on the status of neighboring seats, and the Row is where all that data is stored. When we click on a Seat, that data is passed back up to the Row, which updates the status and passes the status back down to the Seat.
If we add the subtotal calculator, which would be a sibling component to the rows, the situation gets even more complicated. The click event on a Seat would need to be passed all the way back up to the Venue and then down to the subtotal calculator. Similarly, a click on the “Clear All” button would need to be passed up to the Venue and down to all the rows to clear all of the user’s seats.
Here’s a diagram:
Get hands-on with 1200+ tech skills courses.