0

I'm trying to update the state directly inside the return without using any of the life cycle method and am getting error like this:

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.

I referred to this link for the above error, but I didn't get an appropriate solution. Is it always necessary to use a function or life cycle method to update the state?

import React, { Component } from "react";

import "./App.css";

class App extends Component {
  state = {
    name: "john"
  };

  render() {
    console.log(this.state);
    return (
      <div className="App">
        <header className="App-header">
          {this.state.name}
          {this.setState({ name: "abc" })}
        </header>
      </div>
    );
  }
}

export default App;

I wrote the above code and am getting the error but in console the state value is getting update and printing it in many times.

2 Answers 2

2
  1. You have this error because setState triggers re-render of the component each time when your component renders. This causes an endless loop of updates.

    setState() will always lead to a re-render unless shouldComponentUpdate() returns false.

  2. Yes, it is necessary to use a function or life cycle method to update the state. You must not update a state directly in a render function. You should prepare your data for rendering before render and you should update a state in lifecycle methods or in callbacks.

Sign up to request clarification or add additional context in comments.

Comments

0

This is because you are using setState inside the render method. You cannot use setState inside the render method because it will cause the Component to re-render again and again. Because in react application a Component get re-rendered only if Props pass to that component or when setState is called.

So you can use componentDidMount life-cycle to set the state.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.