In this lesson I refactor a React component that uses local state to use Unstated. Unstated provides a very nice and straight-forward API to help you manage global state painlessly.
Instructor: [00:00] I have a couple of components here that derive state and handlers from a common parent component called app. As you can see, app holds the state and handlers locally for us to pass down props for our child components to consume. The list component simply shows a list of items. The actions component has handlers to add and remove items from that list.
[00:22] This is the official way to manage state in our React application, and it works great for most situations. However, there are times where your app may not have a common parent component to contain state, or your app is complex enough it might be better with more conventions for global state.
[00:37] Just a disclaimer. This small app is perfectly fine how it is using set state, but for learning purposes, we'll refactor it to use unstated instead. First, we'll import the three components we're going to need. We'll do import container, provider, subscribe.
[00:55] Container looks much like a normal class component but without the render method. It also allows us to subscribe to the container from within our components, which I'll do in just a second.
[01:04] First, I'll go ahead and rename the app component to the item container. We'll make it extend the container instead and remove the render method.
[01:13] Next, to refactor the list and actions components to subscribe to the item container. We do this by using the subscribe component which requires a two-property for us to subscribe to one or more containers. It also provides a render prop we can use to hook up our components with data and logic from the container.
[01:33] Now, to refactor the actions component to subscribe to the item container and set up the render prop like we did before. Because the add and remove handler methods are no longer being passed as props, we invoke them on the item property which is an instance of item container.
[01:53] Last, I'll adjust the main render method to utilize the provider component and pass the list and action components to it as children, and it looks like it works again.
[02:04] Unstated solves many of the problems Redux, MobX, and other libraries solve. I personally find it very straightforward to get started and love the simplicity. Check out the unstated docs for more info and cases for when to pull it into your project.
Small addendum after recording this video, I should have named the
itemproperty in the render prop function something more explicit to denote it's coming from a container / store. I think a better name for this property would have been
Ie: itemStore.state.items or itemStore.add()