Skip to content

Instantly share code, notes, and snippets.

@adithyamaheshb
Created June 7, 2018 03:43
Show Gist options
  • Save adithyamaheshb/df21c246f1af7b9713a02ee1359a4561 to your computer and use it in GitHub Desktop.
Save adithyamaheshb/df21c246f1af7b9713a02ee1359a4561 to your computer and use it in GitHub Desktop.
Component LifeCycle methods in React
import React, { Component } from 'react';
import LifeCycle from './LifeCycle';
class App extends Component {
constructor(props) {
super(props);
this.state = {
counter: 0
};
this.incrementCounter = this.incrementCounter.bind(this);
}
incrementCounter() {
this.setState({
counter: ++this.state.counter
});
}
render() {
return (
<div>
<LifeCycle counter={this.state.counter} />
<button onClick={this.incrementCounter}>Click</button>
</div>
)
}
}
import React, { Component } from 'react';
class LifeCycle extends Component {
constructor(props) {
super(props);
console.log("constructor", "props :", props);
}
componentWillMount() {
//Fires before render
console.log("componentWillMount is fired");
}
componentDidMount() {
//Fires after first render
console.log("coponentDidMount is fired");
}
componentWillReceiveProps(nextProps) {
//Fires when component will recieve new props from parent
console.log("componentWillRecieveProps fired, nextProps:", nextProps);
}
shouldComponentUpdate(nextProps, nextState) {
//Return true or false based on certain conditions
console.log("shouldCoponentUpdate is fired");
return true;
}
componentWillUpdate(nextProps, nextState) {
//Fires just before rendering takes place in DOM
console.log("componentWillUpdate, nextProps:", nextProps, " nextState:", nextState);
}
componentDidUpdate(nextProps, nextState) {
//Fires immediately after rendering takes place
console.log("componentDidUpdate, prevProps:", prevProps, " prevState:", prevState);
}
render() {
return (
<div>
Counter value: {this.props.counter}
</div>
);
}
}
export default LifeCycle;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment