Today I found something like which I was not expected. This does not happen in Angular or maybe another JS library/framework. But today I was shocked when React lifecycle methods not triggered. Is there some hack behind it. let's see the code.
I have a component A
import React, { Component } from 'react'
class A extends Component {
componentDidMount() {
console.log('component mount', this.props.name);
}
render() {
return (
<>
Hello - {this.props.name}
</>
)
}
}
export default A;
I initialized that component twice in App component with some conditions:
import React, { Component } from 'react';
import { render } from 'react-dom';
import A from './A';
import './style.css';
class App extends Component {
constructor() {
super();
this.state = {
isShow: true
};
this.setIsShow = this.setIsShow.bind(this);
}
setIsShow() {
this.setState(() => {
return {isShow: !this.state.isShow};
});
}
render() {
return (
<div>
<button onClick={this.setIsShow}>Show A1</button>
<button onClick={this.setIsShow}>Show A2</button>
<br />
<br />
{this.state.isShow ? <A name="A1" />
:
<A name="A2" />
}
</div>
);
}
}
render(<App />, document.getElementById('root'));
Now, what is expected behavior? name props value changed when I clicked on buttons. that's expected, alright. But there is no lifecycle method called when component reinitialized :(. The componentDidMount fire only once.
Now add key property in A component selector and you will see componentDidMount called on every time whenever A component reinitialized.
{
this.state.isShow ? <A name="A1" key="1" />
:
<A name="A2" key="2" />
}
This is the expected behavior. But the question is why not without key property.
Checkout Online demo: https://stackblitz.com/edit/problem-react-lifecycle