Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

Unsubscribe in a React Component Using Redux

Aug 27, 2020 • 5 Minute Read

Introduction

To use Redux state management in a React app, you can use a popular library called react-redux, a handy option to configure Redux in your app. When you use Redux, various actions can be triggered, and based on the response, data gets managed in a global state through the action subscription and unsubscription mechanisms. In this guide, you will learn about the subscribe and unsubscribe actions using Redux.

Why Do You Need to Unsubscribe an Action?

It's possible that when one component loads, it can trigger many actions. The action will be subscribing until a response comes, which can lead to a huge bottleneck or memory leaks.

So, its always advisable to unsubscribe an action as soon as the component gets unmounted.

Subscribing an Action

Before using server data, you always need to trigger a network call via an HttpRequest provider such as fetch() or other third-party provider like Axios.

The best way to implement the action subscription is with componentDidMount() because it triggers before the actual initialization of the component and DOM nodes.

For example, you can use Axios to make the API calls. Install it using the below NPM command.

      npm install axios
    

After installing the Axios package, implement a network call, as shown below.

      componentDidMount() {
    var self = this;
    axios
      .get("https://jsonplaceholder.typicode.com/users")
      .then(function(response) {
        self.setState({ users: response.data });
      })
      .catch(function(error) {
        console.log(error);
      })
      .finally(function() {
        // Always executed with the try block
      });
}
    

The above example uses axios.get() followed by the API URL, which fetches the data from the server and returns the response.

You can call this action subscription, but make sure to unsubscribe it from componentWillUnmount().

Subscribing Actions Using Redux Store

You won’t be able to access the store or dispatch the action until and unless you subscribe to the actions from the Redux store.

The store created using createStore() by providing the combined reducer object is shown below.

      import { createStore, combineReducers } from "redux";
import { todos } from "../reducers";

export default () => {
  const rootReducer = combineReducers({
    todos
  });

  // Complete store object
  return createStore(rootReducer);
};
    

In the above example, combineReducers() accepts the list of reducers present in-app and combines them. It represents the ordinary object of the state given to the createStore().

Now, you can subscribe to an action directly after creating the store, as given below.

      const unsubscribeMe = store.subscribe(() => console.log(store.getState()))
    

store.getState() accesses the global state object from the store, and it gets subscribed to your app. It always returns the function to unregister the listener.

The next step is to dispatch any actions, as shown below.

      store.dispatch(addTodo('todo 1'))
store.dispatch(addTodo('todo 2'))
    

The action addTodo() was executed twice and subscribed as well. Now when you don’t want to listen to the action, you can easily unsubscribe it as shown below.

      unsubscribe()
    

Using the above line of code, you are notifying the store that the action dispatched is no longer needed and needs to get unsubscribed.

Unsubscribe or Abort Actions From the Component

The store can be created and subscribed directly using the subscribe() method, which you have already learned in this guide. But what if you want to unsubscribe the action from the component?

Yes, there is a provision to do this using the props subscribe coming from the store as shown below.

      componentDidMount() {
    const { subscribe } = this.props.store;
    this.unsubscribe = subscribe(this.forceUpdate);
}
    

From the command componentDidMount(), the subscriber accessed this.props.store, which was used to subscribe to a store to fetch the state data.

And if you want to unsubscribe an action from the current component, this can be done as shown below.

      componentWillUnmount() {
    this.unsubscribe();
}
    

Include this.unsubscribe() because once you subscribe to the store, it returns the unregister function literally, which is used to unsubscribe the actions and stores once component gets unloaded.

Alternatively, you can pass the store to all the connected components so that any component in your React app can access it seamlessly.

Conclusion

Redux comes with various options, particularly react-redux, that provide the mechanism of the store and connect () functions that return the state and action dispatcher to each component so that it can easily be subscribed and unsubscribed when no longer needed.

I hope that the react-redux store mechanism and action unsubscription covered in this guide will help you to stop app memory leaks.