Chen Jian's Java Blog 

React Component: A pair of componentDidMount() and componentWillUnmount() may cause infinite loop if error is thrown from render

by Chen Jian


Posted on 2019-04-18 13:09 in Frontend


The following will cause an infinite loop. The render() method will be called again and again.

class ToDoItemEditComponentContainer extends React.Component {
    componentDidMount() {        
        this.props.loadItem();  //load item remotely and put it in the local redux store      
    }

    componentWillUnmount() {
        this.props.clearItemLocally(); //remove item from local redux store
    }

    render() {
        throw "some error" 
    }
}

Here is why: "As of React 16, errors that were not caught by any error boundary will result in unmounting of the whole React component tree. " (See here). To be more specific,

  • render() throws an error
  • The react component tree is unmounted
  • componentWillUnmount() is called. And something is cleared from the reduxt store or react state
  • The component tree will be rendered again since some state has been changed

To fix: Implement componentDidCatch() hook in this component or create a global error boundary as shown in here . When there is a render() error, do not call the render() method any more, or do not change any local data in componentWillUnmount()



No one has commented yet.
该日志评论功能被禁用了。