component did mount react code example
Example 1: react native class component constructor
import React from 'react';
import { View, TextInput } from "react-native";
class App extends React.Component {
constructor(props){
super(props);
this.state = {
name: ""
}
this.handleChange = this.handleChange.bind(this);
}
handleChange(text){
this.setState({ name: text })
console.log(this.props);
}
render() {
return (
<View>
<TextInput
value={this.state.name}
onChangeText={(text) =>this.handleChange(text)}
/>
</View>
}
}
export default App;
Example 2: react lifecycle example
class Test extends React.Component {
constructor() {
console.log('Constructor')
super();
this.state = {
count: 0
};
}
componentDidMount() {
console.log("component did mount");
}
componentDidUpdate() {
console.log("component did update");
}
onClick = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
console.log("render");
return (
<div>
Hello Test
<button onClick={this.onClick}>
{this.state.count}
</button>
</div>
);
}
}
//--for first time
//Constructor
//render
//component did mount
//--for any update
//render
//component did update
Example 3: lifecycle method react
INITIALIZATION= setup props and state
MOUNTING= constructor->componentWillMount->render->componentDidMount//Birth
UPDATE= shouldComponentUpdate->componentWillUpdate->render
->componentDidUpdate //Growth
UNMOUNTING= componentWillUnmount //Death
Example 4: shouldcomponentupdate
shouldComponentUpdate(nextProps, nextState) {
return true;
}
Example 5: component did mmount
componentDidMount()
Example 6: component did mmount
componentDidUpdate(prevProps, prevState, snapshot)