~/Home ~/Notes ~/Categories

React Lifecycle Methods

1 September, 2020  ·   React
  https://www.udemy.com/course/modern-react-bootcamp/

Note: These notes are taken from Colt steele’s Modern React Bootcamp course

React Component Lifecycle

Mounting

These methods are called in the following order

constructor()

Often used for initializing state or binding event handlers to class instance.

 1class MyComponent extends Component {
 2  constructor(props) {
 3    super(props);
 4    this.state = {
 5      count: 0,
 6      value: "Hey There!",
 7    };
 8
 9    this.handleClick = this.handleClick.bind(this);
10  }
11}

render()

After the constructor, React calls render(). It tells React what should be displayed. React updates the DOM to match the output of render().

componentDidMount()

1class Clock extends Component {
2  componentDidMount() {
3    this.timerID = setInterval(() => {
4      this.tick();
5    }, 1000);
6  }
7
8  // ...
9}

componentDidMount is also quite useful for making AJAX requests when the component is mounted

 1class GitHubUserInfo extends Component {
 2  componentDidMount() {
 3    axios.get("https://api.github.com/users/facebook").then((response) => {
 4      let user = response.data;
 5      this.setState({ user });
 6    });
 7  }
 8
 9  // ...
10}
1class GitHubUserInfo extends Component {
2  async componentDidMount() {
3    let response = await axios.get("https://api.github.com/users/elie");
4    let user = response.data;
5    this.setState({ user });
6  }
7
8  // ...
9}

Updating

This a suitable place to implement any side effect operations.

This is the order of methods called when a component is being re-rendered:

componentDidUpdate()

1componentDidUpdate(prevProps, prevState) {
2  // you can call setState here as well if you need!
3}

Unmounting

componentWillUnmount()

 1class Clock extends Component {
 2  componentDidMount() {
 3    this.timerID = setInterval(() => {
 4      this.tick();
 5    }, 1000);
 6  }
 7
 8  componentWillUnmount() {
 9    clearInterval(this.timerID);
10  }
11
12  // ...
13}

Error Handling

These methods are called when there is an error during rendering, in a lifecycle method, or in the constructor of any child component.


Visualize component lifecycle

 react  javascript  es6
React Forms↠ ↞Basic Math Theory