Subscribing to Store Updates

Up until here we have dispatched our actions, made sure the reducer received them and then responded with updates. The next step is to receive a notification of the update using store.subscribe().

When you visit the bank, let the Cashier know your intended WITHDRAWAL action, and successfully receive your money, what next?

Most likely, you will receive an alert via email/text or some other mobile notification saying you have performed a transaction, and your new account balance is so and so.

If you don’t receive mobile notifications, you’ll definitely receive some sort of ‘personal receipt’ to show that a successful transaction was carried out on your account.

Okay, note the flow. An action was initiated, you received your money, you got an alert for a successful transaction.

We seem to be having a problem with our Redux code. An action has been successfully initiated, we’ve received money (state), but hey, where’s the alert for a successful state update?

We’ve got none.

Well, there’s a solution. Where I come from, you subscribe to receive transaction notifications from the bank either by email/text.

The same is true for Redux. If you want the updates, you’ve got to subscribe to it. But how?

The Redux store, whatever store you create has a subscribe method called like this: store.subscribe().

Well named function, if you ask me!

The argument passed into store.subscribe() is a function, and it will be invoked whenever there’s a state update. For what it’s worth, please remember that the argument passed into store.subscribe() should be a function. Okay?

Now let’s take advantage of this.

Think about it. After the state is updated, what do we want or expect? We expect a re-render, right?

So, state has been updated. Redux, please, re-render the app with the new state values.

Let’s have a look at where the app is being rendered in index.js Here’s what we’ve got.

ReactDOM.render(<App />, document.getElementById("root")

This is the line that renders the entire application.

It takes the <App/> component and renders it in the DOM. The root ID to be specific.

First, let’s abstract this into a function. See this:

Get hands-on with 1200+ tech skills courses.