Listening to Updates

Learn how to update the store.

Now that we know how the store updates the state, we need to update the UI or other parts of our application when the state changes. The store allows us to subscribe to state changes using the subscribe() method. It accepts a callback function, which will be executed each time an action is dispatched:

const store = createStore((state) => state);

const onStoreChange = () => console.log(store.getState());

store.subscribe(onStoreChange);

The callback in subscribe() does not receive any arguments, so we must call store.getState() ourselves to access the state.

The return value of the subscribe() method is a function that can be used to unsubscribe from the store. It is important to remember to call unsubscribe() for all subscriptions to prevent memory leaks:

const unsubscribe = store.subscribe(onStoreChange);

// When the subscription is no longer needed
unsubscribe();

Get hands-on with 1200+ tech skills courses.