i am learning react for last 3 month and didn't get 1 things clearly..i wanted to know that if my top level app component get new props but didn't call any set State...is it gonna call the component Did Mount??or it will not call any component Did Mount..
It won't call componentDidMount
again if the component is already mounted, no. But it will (for now) call the old componentWillReceiveProps
/UNSAFE_componentWillReceiveProps
, and will call render
and componentDidUpdate
.
It's easy to try these things out. for example:
class Parent extends React.Component {
constructor(props) {
super(props);
console.log("Parent - constructor");
}
componentDidMount() {
console.log("Parent - componentDidMount");
}
UNSAFE_componentDidReceiveProps() {
console.log("Parent - UNSAFE_componentDidReceiveProps");
}
componentDidUpdate() {
console.log("Parent - componentDidUpdate");
}
render() {
console.log("Parent - render");
const { value } = this.props;
return <Child value={value} />;
}
}
class Child extends React.Component {
constructor(props) {
super(props);
console.log("Child - constructor");
}
componentDidMount() {
console.log("Child - componentDidMount");
}
UNSAFE_componentDidReceiveProps() {
console.log("Child - UNSAFE_componentDidReceiveProps");
}
componentDidUpdate() {
console.log("Child - componentDidUpdate");
}
render() {
console.log("Child - render");
const { value } = this.props;
return <div>value = {value}</div>;
}
}
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
counter: 0
};
}
componentDidMount() {
setTimeout(() => {
this.timer = setInterval(() => {
this.setState(({counter}) => {
++counter;
if (counter === 2) {
clearInterval(this.timer);
}
return {counter};
});
}, 500);
}, 1000);
}
render() {
const { counter } = this.state;
return <Parent value={counter} />;
}
}
ReactDOM.render(<Example />, document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js"></script>