0
votes

I'm new to React Hooks. And this warning is shown when I jump from section About to another section. Without wait for it to finish to mount.

index.js:1 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. in FadeItems (at AboutSection.jsx:32) in div (created by CardBody) in CardBody (at AboutSection.jsx:29) in div (created by Card) in Card (at AboutSection.jsx:22) in div (at AboutSection.jsx:19) in AbouSection (at About.jsx:9) in section (at About.jsx:7) in About (created by Context.Consumer)

Here is the code for FadeItems:

import React, { useState } from "react";
import PropTypes from "prop-types";
import { Fade } from "reactstrap";

const FadeItems = (props) => {

  const [count, setCount] = useState(0);

  // const [mount, setMount] = useState(true);
  // useEffect(() => {
  //   // setTimeout(() => {
  //     // let mounted = true
  //       if (mount) {
  //         mount = false;
  //       }

  //     return function cleanup() {
  //         mounted = false
  //     }
  //     // setCount(0);
  //   // }, 300)
  // }) // prevent the unmounted component to be updated

  const { text } = props;
  return (
    <div style={{ backgroundColor: '#282c34', padding: '30px', borderBottom: "solid 2px #764abc"}}>
      {
        text.map((statement, index) => (
          <Fade
            in={count >= index ? true : false}
            onEnter={() =>
              setTimeout(() => {
                setCount(index + 1);
              }, 2000)
            }
            onExiting={() => setCount(-1)}
            tag="h5"
            className="mt-3"
            key={index + 100}
            style={{ backgroundColor: '#282c34' }}
          >
            {statement}
          </Fade>
        ))
      }
    </div>
  );
};

FadeItems.propTypes ={
  text: PropTypes.string,
}.isRequired;

export default FadeItems;

I have a timer set to mount Fade after 2 seconds. Which is called by the props onEnter. After it mounts. As suggests the Reacstrap documentation here:

Fade item documentation Reactstrap

The commented section on code was an attempt to fix with useEffect. But I don't know how to use it properly yet. If you want to check the repository:

GitHub Repository

1

1 Answers

1
votes

You need to clear the set timer in cleanup function of useEffect

 const [mount, setMount] = useState(true);
   useEffect(() => {
      const timerId = setTimeout(() => {
        let mounted = true
         if (mount) {
           mount = false;
         }

      return () => {
         clearTimeout(timerId);
      }
   })