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 ...