what are life cycle methods in react code example
Example 1: 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 2: lifecycle methods react
Every component in React goes through a lifecycle of events. I like to think of them as going through a cycle of birth, growth, and death.
Mounting – Birth of your component
Update – Growth of your component
Unmount – Death of your component
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);
}
Example 5: react lifecycle hooks
class ActivityItem extends React.Component {
render() {
const { activity } = this.props;
return (
<div className='item'>
<div className={'avatar'}>
<img
alt='avatar'
src={activity.actor.avatar_url} />
</div>
<span className={'time'}>
{moment(activity.created_at).fromNow()}
</span>
<p>{activity.actor.display_login} {activity.payload.action}</p>
<div className={'right'}>
{activity.repo.name}
</div>
</div>
)
}
}