Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Use Unstated for State Management in React


    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.

    Additional Resources:



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




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

    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.

    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.

    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.

    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.

    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.

    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.

    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.

    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.