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.