react js lifecycle hooks code example
Example 1: set state
class App extends React.Component {
state = { count: 0 }
handleIncrement = () => {
this.setState({ count: this.state.count + 1 })
}
handleDecrement = () => {
this.setState({ count: this.state.count - 1 })
}
render() {
return (
{this.state.count}
)
}
}
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: set state
setState({ searchTerm: event.target.value })
Example 4: react lifecycle hooks
class Content extends React.Component {
// ...
componentWillMount() {
this.setState({ activities: data });
}
// ...
}
Example 5: 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}
)
}
}