Simpleton Simpleton - 2 years ago 162
Javascript Question

Too much recursion when updating state in react

In this example, when I try to update the state during the

life cycle callback, I get a
too much recursion
error. How should I be updating the state?

import React from 'react';

class NotesContainer extends React.Component {
constructor(props) {
this.state = { listOfShoppingItems: [] };

componentDidUpdate(nextProps, nextState) {
let newShoppingItems = this.calculateShoppingItems();
this.setState({ listOfShoppingItems: newShoppingItems });

calculateShoppingItems() {
let shoppingItemsCart = []

if (this.props.milk < 3) {
let value = "Buy some milk";

if (this.props.bread < 2) {
let value = "Buy some bread";

if (this.props.fruit < 10) {
let value = "Buy some fruit";

if (this.props.juice < 2) {
let value = "Buy some juice";

if (this.props.sweets < 5) {
let value = "Buy some sweets";

return shoppingItemsCart;

render() {
return (

export default NotesContainer;

Answer Source

componentDidUpdate is triggered when either the props or the state has changed. If you change the state in this method, you are causing an infinite loop (unless you implement shouldComponentUpdate).

It looks like your state changes when you receive new props, therefore componentWillReceiveProps seems a good place. From the docs:

Invoked when a component is receiving new props. This method is not called for the initial render.

Use this as an opportunity to react to a prop transition before render() is called by updating the state using this.setState(). The old props can be accessed via this.props. Calling this.setState() within this function will not trigger an additional render.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download