component did mount code example
Example 1: how to use componentdidmount in functional component
// passing an empty array as second argument triggers the callback in useEffect
// only after the initial render thus replicating `componentDidMount` lifecycle behaviour
useEffect(() => {
if(!props.fetched) {
props.fetchRules();
}
console.log('mount it!');
}, []);
// componentDidUpdate
useEffect({
your code here
})
// For componentDidUpdate
useEffect(() => {
// Your code here
}, [yourDependency]);
// For componentWillUnmount
useEffect(() => {
// componentWillUnmount
return () => {
// Your code here
}
}, [yourDependency]);
Example 2: 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 3: componentDidUpdate
componentDidUpdate(prevProps, prevState) {
if (prevState.pokemons !== this.state.pokemons) {
console.log('pokemons state has changed.')
}
}
Example 4: 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 5: prev props
componentDidUpdate(prevProps) {
// Utilisation classique (pensez bien à comparer les props) :
if (this.props.userID !== prevProps.userID) {
this.fetchData(this.props.userID);
}
}
Example 6: lifecycle method react
INITIALIZATION= setup props and state
MOUNTING= constructor->componentWillMount->render->componentDidMount//Birth
UPDATE= shouldComponentUpdate->componentWillUpdate->render
->componentDidUpdate //Growth
UNMOUNTING= componentWillUnmount //Death