Search code examples
javascriptreactjsimageorientationsetstate

Repeatedly calling setState inside componentWillUpdate or componentDidUpdate?


I'm trying to figure out the orientation of background-images in a React component that are passed in as props.

I start off by creating an Image object and setting its src to the new Image:

  getImage() {
    const src = this.props.url;
    const image = new Image();
    image.src = src;

    this.setState({
      height: image.height,
      width: image.width
    });
  }

After I've updated the state with the heights and widths, I try calling getOrientation() inside of componentDidUpdate():

  getOrientation() {
    const { height, width } = this.state;
    if (height > width) {
      this.setState({ orientation: "portrait" });
    } else {
      this.setState({ orientation: "landscape" });
    }
  }

I then get the following error:

Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate.

Any ideas what's going on here?

Link to Sandbox


Solution

  • The valid function signature of componentDidUpdate is:

    componentDidUpdate(prevProps, prevState, snapshot)
    

    Note that the arguments have to be in the correct order. Here you can see that the previous props is the first argument, and the previous state the second one.

    If you only have componentDidUpdate(prevState) then the variable prevState refers to the previous props, not the previous state. And so, to position them correctly, you need to include prevProps first (even if you will not use it):

    componentDidUpdate(prevProps, prevState) {
      ...
    }
    

    For more information, see the React.Component documentation.