Rami Chasygov
Rami Chasygov

Reputation: 2784

Maximum call stack size exceeded React-Redux

I have error maximum call stack size exceeded. Maybe I in wrong way understand componentDidUpdate, but shouldn't it's run one time, instead 1000. How fix it?

class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      amount: 0
    }
  }

  updateAmout() {
    let number = 0;
    this.props.comments.map((comment, index) => {

      if (comment.replyTo === null) {

        number += 1;
        this.setState({amount: number});
      }
      return null;
    });
  }

  componentWillMount() {
    this.updateAmout();
  }

  componentDidUpdate() {
    this.updateAmout();
  }

  render() {
    console.log(this.state.amount);
    return (
      <div className="comments-container">
        <div id="comments">
          <AddComment />
          <div className="comments-flow">
            <div className="comments-header">
              <div className="pull-right">
                <a href="" className="text-muted">Best</a> |
                <a href="" className="active">Newest</a> |
                <a href="" className="text-muted">Oldest</a>
              </div>
              <b>6 Comments</b>
            </div>
            <RenderComments />
          </div>
          <button className="btn btn-block">More...</button>
        </div>
      </div>

    ) // return
  } // render
} // App

Upvotes: 4

Views: 10553

Answers (2)

Rami Chasygov
Rami Chasygov

Reputation: 2784

I found the answer to my question. I need to use the nextProps argument and the method componentWillUpdate instead of the componentDidUpdate method.

// before
componentDidUpdate() {
 this.updateAmout();
}

// after
componentWillUpdate(nextProps) {
  if (!_.isEqual(this.props, nextProps)) {
    this.updateAmout();
  }
}

Upvotes: 1

Dez
Dez

Reputation: 5838

Each time you modify state in componentDidUpdate, a re-render is thrown asynchronously. In your method updateAmount, you are modifying the state. And you are calling that method in componentDidUpdate, so you initiate an infinite loop of re-renders, so this endless loop created finally wastes the javascript memory.

The React cycle when updating the state is the following one. So you can easily understand why you enter into an endless loop. enter image description here

Upvotes: 6

Related Questions