1

I'm trying to understand when componentWillUnmount is called. I have this class-based component:

class ClassComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = { date: new Date().toLocaleString() };
    }

    componentDidMount() {
        console.log('mounted');
    }

    componentWillUnmount() {
        console.log('unmounting');
    }

    render() {
        return <div></div>;
    }
}
export default ClassComponent;

But when I check the console, it already prints "unmounting" although the component is still mounted. In total I have three logs in the console:

mounted unmounting mounted

Can someone explain to me why that is the case?

Sam
  • 41
  • 3
  • To understand more clearly what is going on you will need to include the renderer of `ClassComponent` in your question, it's likely the dual mounting you're seeing is cause in there – Marc Costello Aug 17 '22 at 19:06
  • I'm not sure I understand that correctly. Are you referring to the parent? That would be App.js in my case and renders the component conditionally on button click – Sam Aug 17 '22 at 19:26

1 Answers1

2

Found the reason, it is due to the new strict-mode behaviors: https://reactjs.org/blog/2022/03/29/react-v18.html#new-strict-mode-behaviors

Sam
  • 41
  • 3