Author avatar

Gaurav Singhal

Unsubscribe in a React Component Using Redux

Gaurav Singhal

  • Aug 27, 2020
  • 5 Min read
  • 900 Views
  • Aug 27, 2020
  • 5 Min read
  • 900 Views
Web Development
Front End Web Development
Client-side Frameworks
React

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.

1
npm install axios
shell

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
      });
}
jsx

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.

1
2
3
4
5
6
7
8
9
10
11
import { createStore, combineReducers } from "redux";
import { todos } from "../reducers";

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

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

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.

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

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.

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

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.

1
unsubscribe()
js

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.

1
2
3
4
componentDidMount() {
    const { subscribe } = this.props.store;
    this.unsubscribe = subscribe(this.forceUpdate);
}
jsx

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.

1
2
3
componentWillUnmount() {
    this.unsubscribe();
}
jsx

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.

1