life cycle hooks in react code example
Example 1: setstate react js
constructor(props) {
super(props);
this.state = {
isActive: true,
};
}
checkStatus = () => {
this.setState({ // use this function
'isActive' : !this.state.isActive,
});
}
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 (
Hello Test
);
}
}
//--for first time
//Constructor
//render
//component did mount
//--for any update
//render
//component did update
Example 3: 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 4: lifecycles if reactjs
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
componentDidMount() { }
componentWillUnmount() { }
render() {
return (
Hello, world!
It is {this.state.date.toLocaleTimeString()}.
);
}
}
Example 5: react lifecycle hooks
class Content extends React.Component {
// ...
componentWillMount() {
this.setState({ activities: data });
}
// ...
}
Example 6: react lifecycle hooks
class ActivityItem extends React.Component {
render() {
const { activity } = this.props;
return (
{moment(activity.created_at).fromNow()}
{activity.actor.display_login} {activity.payload.action}
{activity.repo.name}
)
}
}