How can I check if the component is unmounted in a functional component?

brainmassage

A callback function sets the component state. But sometimes subscription which supplies the data need to end. Because callback is executed asynchronously, it's not aware if the subscription ends just after making the service call (which executes the callback function).

Then I see following error in the console:

Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

Is there a way to access the component state, even if I am in the callback function?

This would be the steps:

  • subscribe with parameters
  • unsubscribe
  • component is unmounted
  • subscribed service executes the callback function
  • callback functio sets state in an unmounted component and it gives error above
HMR

Here is some pseudo code how you can use useEffect to see if a component is mounted.

It uses useEffect to listen to someService when it receives a message it checks if the component is mounted (cleanup function is also called when component unmounts) and if it is it uses setServiceMessage that was created by useState to set messages received by the service:

import { useState, useEffect } from 'react';
import someService from 'some-service';

export default props => {
  const userId = props.userId;
  const [serviceMessage, setServiceMessage] = useState([]);
  useEffect(
    () => {
      const mounted = { current: true };
      someService.listen(
        //listen to messages for this user
        userId, 
        //callback when message is received
        message => {
          //only set message when component is mounted
          if (mounted.current) {
            setServiceMessage(serviceMessage.concat(message));
          }
      });
      //returning cleanup function
      return () => {
        //do not listen to the service anymore
        someService.stopListen(userId);
        //set mounted to false if userId changed then mounted
        //  will immediately be set to true again and someService
        //  will listen to another user's messages but if the 
        //  component is unmounted then mounted.current will 
        //  continue to be false
        mounted.current = false;
      };
    },//<-- the function passed to useEffects
    //the function passed to useEffect will be called
    //every time props.userId changes, you can pass multiple
    //values here like [userId,otherValue] and then the function
    //will be called whenever one of the values changes
    //note that when this is an object then {hi:1} is not {hi:1}
    //referential equality is checked so create this with memoization
    //if this is an object created by mapStateToProps or a function
    [userId]
  );
};

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How can I refresh React Functional component?

How can I access methods of a component using ref in functional component

How can I make a component render onClick in a React functional component?

How can I convert class component to functional component?

React: How can I acces to props of a functional component in a class component

Warning: Can't perform a React state update on an unmounted component. In a functional component

can't setState on an unmounted component

How can I cancel a state change from a resolving promise after component is already unmounted?

How do I avoid "Can't perform a React state update on an unmounted component" error on my application?

How can I remove event Listener so it would not try to update state when component is unmounted?

How can I prevent a React state update on an unmounted component in my integration testing?

React: how can I force state to update in a functional component?

How can I set State based on other state in functional component?

How can i filter an state array in functional component in react native

How Can I extend a React functional Component Prop Type?

how i can change this code to functional component in react

How can I use {...this.props} in a functional component

How can I use forwardRef in functional component in react native?

How can I receive data that was sent by express on functional component?

How can i unmount a functional component from DOM on click on a Button

How I can manage the state for 4 Checkbox in functional component in ReactJS?

how can i pass functional react component to a function?

How can I export state to parent functional component in React?

How do I retain state in a React component that gets mounted and unmounted?

reactjs: is there public API to check if the component is mounted/unmounted

Can I make a functional component in Hyperstack?

ReactJS - How can I transform a Class Component withsSide-effects of combined state updates to a Functional Component

How can I convert popover MATERIAL-UI functional component to class based component?

How can I change this functional component into a class based component in react native?