react lifecycle methods in functional components code example
Example 1: how to use componentdidmount in functional component
useEffect(() => {
if(!props.fetched) {
props.fetchRules();
}
console.log('mount it!');
}, []);
useEffect({
your code here
})
useEffect(() => {
}, [yourDependency]);
useEffect(() => {
return () => {
}
}, [yourDependency]);
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>
);
}
}
Example 3: lifecycle method react
INITIALIZATION= setup props and state
MOUNTING= constructor->componentWillMount->render->componentDidMount
UPDATE= shouldComponentUpdate->componentWillUpdate->render
->componentDidUpdate
UNMOUNTING= componentWillUnmount
Example 4: react lifecycle
constructor(props) {
super(props);
this.state = { counter: 0 };
this.handleClick = this.handleClick.bind(this);
}