The following code example contains 2 components: Component1 logs prevState with componentDidUpdate method, Component2 is removed on a button click to show the use of componentWillUnmount.
const { useState } = React;
class Component1 extends React.Component {
constructor(props) {
super(props);
this.state = {
name: 'John',
};
}
componentDidUpdate(prevProps, prevState) {
console.log(prevState);
}
render() {
return (
<div>
<div>The name is {this.state.name}</div>
<label htmlFor="prevstate">Type here to see prevState in console: </label>
<input
id="prevstate"
onChange={(e) => {
this.setState({ name: e.target.value });
}}
/>
</div>
);
}
}
class Component2 extends React.Component {
componentDidMount() {
console.log('Mount');
}
componentWillUnmount() {
console.log('Unmount');
}
render() {
return (
<div>
<div>Click the button to remove the element</div>
</div>
);
}
}
const App = () => {
const [showComponent, setShowComponent] = useState(true);
return (
<div>
<Component1 />
{showComponent ? <Component2 /> : null}
<button
onClick={() => {
setShowComponent(false);
}}
>
Remove
</button>
</div>
);
};
// Render it
ReactDOM.render(<App />, document.getElementById('react'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react"></div>
Now I find that these 2 components interfere with each other: clicking the button also logs the prevState in the first component. What I thought would happen was that the componentDidUpdate method would only monitor the update of Component1, but seems it monitors the button which is outside of both components, why does this happen?