Skip to content

Instantly share code, notes, and snippets.

@ross-u
Last active February 26, 2020 16:09
Show Gist options
  • Save ross-u/ce9f84d3f6e2f5b16e52dfb378cf84e0 to your computer and use it in GitHub Desktop.
Save ross-u/ce9f84d3f6e2f5b16e52dfb378cf84e0 to your computer and use it in GitHub Desktop.
React Lifecycle methods - I Mounting - constructor()

React | Lifecycle methods


I - Mounting or First Render

These methods are called in the following order when an instance of a component is created and inserted into the DOM:

  1. constructor()
  2. render()
  3. componentDidMount()

constructor()

  • We use it when we want to pass props to the class component.
  • By default it must contain super keyword, that receives props as argument from constructor.
  • If we are setting the state in constructor we have to use this keyword.
  • We can use it to bind() value of this to the methods.
  • If we are not initializing the state from props and we are not binding methods, we don’t need to use/write the constructor(){ ... } block in our React component.
import React from 'react';
import './App.css';
import Clock from './components/Clock';
class App extends React.Component {
state = {
currentTime: 'N/A',
showClock: true
}
toggleClock = () => {
this.setState({ showClock: !this.state.showClock })
}
render () {
return (
<div className="App">
<button onClick={this.toggleClock}>TOGGLE CLOCK</button>
{
this.state.showClock
? <Clock />
: null
}
</div>
);
}
}
export default App;
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {
year: undefined
};
console.log('IN CONSTRUCTOR');
};
// custom methods and lifecycle methods go after the `constructor`- e.g. `render()`
render() {
return (
<div>
<h1>Clock</h1>
</div>
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment