Why am I getting Invariant Violation: Invariant Violation: Maximum update depth exceeded. on setState?

reactjs setstate maximum update depth exceeded
uncaught invariant violation: maximum update
useeffect maximum update depth exceeded
setstate invariant violation
invariant violation react native setstate
maximum update depth exceeded react-router
component repeatedly calls setstate inside componentwillupdate or componentdidupdate
componentdidupdate error

I have this component:

// imports

export default class TabViewExample extends Component {
  state = {
    index: 0,
    routes: [
      { key: 'first', title: 'Drop-Off', selected: true },
      { key: 'second', title: 'Pick up', selected: false },
    ],
  };

  handleIndexChange = index => this.setState({ index });

  handleStateIndexChange = () => { // FUNCTION WITH THE ERROR
    const { index } = this.state;
    this.setState(({ routes }) => ({
      routes: routes.map((route, idx) => ({
        ...route,
        selected: idx === index,
      })),
    }));
  };

  renderTabBar = props => {
    const { routes } = this.state;
    this.handleStateIndexChange(); // HERE I GET THE ERROR
    return (
      <View style={tabViewStyles.tabBar}>
        {props.navigationState.routes.map((route, i) => {
          return (
            <>
              <TouchableOpacity
                key={route.key}
                style={[
                  tabViewStyles[`tabStyle_${i}`],
                ]}
                onPress={() => this.setState({ index: i })}
              >
                <Text>
                  {route.title}
                </Text>
                // THE FUNCTION ATTEMPTS TO SHOW AN ELEMENT WHEN
                // THE INDEX OF A ROUTE IS selected true
                {routes[i].selected && (
                  <View
                    style={{
                      flex: 1,
                    }}
                  >
                    <View
                      style={{
                        transform: [{ rotateZ: '45deg' }],
                      }}
                    />
                  </View>
                )}
              </TouchableOpacity>
            </>
          );
        })}
      </View>
    );
  };

  renderScene = SceneMap({
    first: this.props.FirstRoute,
    second: this.props.SecondRoute,
  });

  render() {
    return (
      <TabView
        navigationState={this.state}
        renderScene={this.renderScene}
        renderTabBar={this.renderTabBar}
        onIndexChange={this.handleIndexChange}
      />
    );
  }
}

Full error:

Invariant Violation: Invariant Violation: 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.

This is the function giving the error:

  handleStateIndexChange = () => { // FUNCTION WITH THE ERROR
    const { index } = this.state;
    this.setState(({ routes }) => ({
      routes: routes.map((route, idx) => ({
        ...route,
        selected: idx === index,
      })),
    }));
  };

All I need is to set the state of selected to true so I can toggle the visibility of a component.

As stated in the comment above, you cannot call setState directly inside your render function.

I do not see any reason to keep the selected value in your state as it only depends on another value already in it, this information is redundant.

You should remove selected from all your objects in routes and change your JSX condition :

{routes[i].selected &&

To the following :

{i === this.state.index &&

To produce the same result.

You can now remove handleStateIndexChange from your code

React-Native = Invariant Violation: Maximum update depth exceeded, [Mobile] Invariant Violation: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside I will comment again if I get clues for rerender, or Invariant Violation: Maximum update� Invariant Violation: 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.

Because of the way React will batch state updates, if you need to set state based off previous state, you should do all the destructuring in the callback:

  handleStateIndexChange = () => {
    this.setState(({ index, routes }) => ({
      routes: routes.map((route, idx) => ({
        ...route,
        selected: idx === index,
      })),
    }));
  };

Also, as @Adeel mentions, you should not call this.setState from inside the render execution context. Move that call the componentDidUpdate instead.

[Mobile] Invariant Violation: Maximum update depth exceeded , Currently in React 16.8.6, we get this error when changing the state in a This can happen when a component repeatedly calls setState inside Invariant Violation: Maximum update depth exceeded. with hooks #15906. But whenever I run the project It shows the following error- How to solve Invariant violation: maximum update depth exceeded in React-Native? So, I want to know how I can change the Image beside the Title TextInput by click the icons at the bottom of the screen.

Calling setState in render is the actual reason for infinite rerender loop, because setting state calls rerender, which calls another setState which calls another rerender etc.

So I would suggest to move the setState part into componentDidUpdate and control it there. Here is the approximation of what I mean with little changes to describe the point.

class App extends React.Component {
  state = {
    index: 0,
    routes: [
      {
        key: "first",
        title: "Drop-Off",
        selected: true
      },
      {
        key: "second",
        title: "Pick up",
        selected: false
      }
    ]
  };

  componentDidUpdate(_, prevState) {
    if (prevState.index !== this.state.index) {
      this.handleStateIndexChange();
    }
  }

  handleIndexChange = () => {
    const randomIndexBetweenZeroAndOne = (Math.random() * 100) % 2 | 0;

    this.setState({
      index: randomIndexBetweenZeroAndOne
    });
  };

  getMappedRoutes = (routes, index) =>
    routes.map((route, idx) => ({
      ...route,
      selected: idx === index
    }));

  handleStateIndexChange = () => {
    this.setState(({ routes, index }) => ({
      routes: this.getMappedRoutes(routes, index)
    }));
  };

  render() {
    const { routes } = this.state;

    return (
      <>
        <button onClick={this.handleIndexChange}>Change Index</button>
        {this.state.routes.map(JSON.stringify)}
      </>
    );
  }
}

Invariant Violation: Maximum update depth exceeded. with hooks , Invariant Violation Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or� I'm getting a "Invariant Violation: Maximum update depth exceeded." at: CalendarPicker/index.js line: 89 column: 11 name: 'setState' That line is from the code for 'componentDidUpdate', it seems to be getting caught in a loop when initial date is passed.

Occasionally getting: Invariant Violation Maximum update depth , maximum update depth exceeded react native setstate react-dom development js 55 uncaught invariant violation maximum update depth exceeded This can happen when a component repeatedly calls setState inside a nested update error, you get this [Mobile] Invariant Violation: Maximum update depth exceeded. It wasn't caused by setState pointed by CRA though. ryota-murakami mentioned this issue May 27, 2018 [Mobile] Invariant Violation: Maximum update depth exceeded.

[How to fix] Invariant Violation: Maximum update depth exceeded, I keep getting the following error message when I run an Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside� Infinite Loop when maximum update depth exceeds #11136. Maximum update depth exceeded. This can happen when a component repeatedly the App component is

[Error Help Please :D] Maximum update depth exceeded. Not sure , [How to fix] Invariant Violation: Maximum update depth exceeded setState in your render() function. class MyComponent extends React.Component { render() { // don't do this inside render() this. [The easy way] to get url params in a React functional component � [The easy way to] get url params in React� 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. · Issue #1565 · Hacker0x01/react-datepicker · GitHub

Comments
  • You never setState in render directly in this call by calling a function in render that does that.
  • @AdeelImran so am I suppose to call it?
  • setState in render triggers another render which triggers another setState in the loop. It's an antipattern. Try to lift it up into lifecycle methods before render.
  • @KarenGrigoryan If you see my code, I have this this.handleStateIndexChange(); // HERE I GET THE ERROR which is the function I am calling inside renderTabBar which is call on the render method. Also, if I use setState on componentDidMount I get the error that I should not use setState on a componentDidMount function.
  • Sorry, I mean componentDidUpdate not componentDidMount
  • According to @Adeel Imran comment I can not call setState on a render method which is what I am doing. If you see my code, I have this this.handleStateIndexChange(); // HERE I GET THE ERROR which is the function I am calling inside renderTabBar which is call on the render method. Also, if I use setState on componentDidMount I get the error that I should not use setState on a componentDidMount function.
  • Yes @Adeel is correct, calling setState inside render will cause infinite loops. You should be using componentDidUpdate to perform the state update.
  • Sorry, I mean componentDidUpdate not componentDidMount