Instructor: In this example, I have an app component with some state and a couple of handlers. The state has an itemized property which is an array of numbers. The state and handlers are being passed down to two components. One is called list for the list of items and actions for the two handlers add or remove.
The concept of having a parent component manage state and passed down to children components is how React suggest doing things for most of the application needs.
Now, there are some cases where having a tool like Redux, or MobX, or for this example, unstated would be nice to help provide some additional structure to your application. One such use case for one of these tools is where you have an application that has several render points which need to share some global state.
One way to do this is with portals, but for this lesson we'll use unstated. Let's go ahead and add an additional rendering point to our application called Route two, and render the actions and items separately instead of app.
First off, I'm going to separate the list and actions components, so they're no longer under the same parent component, or app in this case. It could no longer share the same state and handlers.
Next to import unstated, this involves importing a container, provider, and subscribe component. Since app is no longer the main parent component, for this example, I'm going to refactor it to use the unstated container instead. We can share its state and handlers between multiple components wherever there DOM maybe.
Notice how the unstated container looks pretty much like a normal react component just without the render method. Next, I'm going to instantiate this new container and assign it to a variable, so we can use it in just a second.
Now, to refactor the list in actions components to subscribe to the container. We do this by using the subscribe component and passing the container in the to property.
The subscribe component implements the render prop pattern, and the app instance that we're passing in the to property will be made available to us. State is found on the state property.
Now, it's refactor the actions component in the same manner. The add and remove methods are found on the apt object, just as state is.
I'll go ahead and adjust each button to utilize the handlers found on the app property. I'm also going to remove the destructured props found in each constructor, since we no longer need them for this example.
Finally, to wrap each of these components with the provider component in our two render functions to make unstated available. We'll also need to dependency inject our app instance in each provider, so it knows to share the same instance between the two. Inject can also help us with testing, but that's for another lesson. That's it.
Maybe you're sprinkling reactant into an existing application, or need a clear way to manage global state. Unstated is a great way to do these things without a complication.