Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

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


    Render React UI Based on State Changes with Subscribe in Redux

    15 - 16
    3 - 4

    The Redux store exposes a subscription mechanism, allowing us to detect state updates. In this lesson, we’ll take advantage of this by rendering our UI in response to state changes. We’ll also get our first look at the dispatch method that will be used to trigger those updates.



    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




    Here, we're using the store's getState method to get the global state out of our store and we're passing it into our app component as props. This happens once when the application loads, but we need to be able to update our application when the state object changes.

    I'm going to start by creating a new function, which I'm going to call render. I'm just going to use arrow-function syntax and then I want to take these two calls and move them into the render function. Then I want to call render so that our application renders on the initial load. I'll save this, the browser will refresh, and we'll get our application back.

    Now that we have this render function, let's subscribe to changes in the store. We're going to do that by calling store.subscribe, and then subscribe takes a function, and we're just going to use our render function. Now anytime there's an update to the state object in the store, subscribe is going to call our render function and update our application.

    Now that we've subscribed to updates, let's trigger an update so we can see it in action. I'm just going to add some temporary code here so that we can dispatch an action and see our update take place. I'm going to use a set timeout and I'm going to pass that a function and a timeout of one second.

    In my set timeout, I'm just going to reference the store and I'm going to call dispatch. The dispatch method is going to call our reducer with our current state, and the action that we pass into dispatch, and that's going to trigger an update to our state, which will call render through the subscribe method.

    We're going to dispatch an action of type todo_add. Then we want to give it a payload, because that's what our reducer is expecting, and that payload is going to be an object that represents a new todo. We'll give it an ID and we'll give it a name. We'll give it an isComplete value, which will be false.

    We'll save this and now our browser will reload and then after a second we'll see that new todo got added.