Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Error: Max update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate

I want to do in class component what I did in function component, but it gives an error. How can I fix?

function component:

const [listBtnClassName, setListBtnClassName] = useState("listBtnPulse");

useEffect(() => {
    if (showGrid) {
      setListBtnClassName("listBtnPulseNone");
    }
  }, [showGrid]);

<PageFilter listBtnClassName={listBtnClassName} ></PageFilter>

class component:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

this.state = {
      listBtnClassName: "listBtnPulse",
    };

 componentDidUpdate() {
    if (this.props.showGrid) {
      this.setState({ listBtnClassName: "listBtnPulseNone" });
    }
  }

<PageFilter listBtnClassName={this.state.listBtnClassName} ></PageFilter>

Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

>Solution :

You need to make sure the showGrid from the previous props is not true, but the showGrid from current props is true.

See this document for more information.

this.state = {
  listBtnClassName: "listBtnPulse",
};

componentDidUpdate(prevProps) {
  if (!prevProps.showGrid && this.props.showGrid) {
    this.setState({ listBtnClassName: "listBtnPulseNone" });
  }
}
<PageFilter listBtnClassName={this.state.listBtnClassName} ></PageFilter>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading