React Lifecycle Methods Flashcards

1
Q

What are lifecycle methods?

A

Every component comes with methods that allows developers to update application state and reflect to ui before/after “key events.”

Not clicking or dragging, but events or stages in the lifecycle of a component.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What happens during mounting?

A

React runs the constructor where the initial state lives. as well as bind event handlers. After that React calls the render. It tells React what to put on page and React updates the DOM to match the output of the render. After that comes componentDidMount().

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is componentDidMount() ?

A

A method we define and React will automatically run it for us when once as the component has mounted. Good place to load any data with AJAX or set up subscriptions/timers.

Calling setState here will trigger re-render so be careful. Doesn’t mean we shouldn’t call setState as we often do but this happens after the render, not before the first render.

class ZenQuote extends Component {
constructor(props) {
super(props);
this.state = {quote: ''}
}
componentDidMount() {
axios.get("https://api.github.com/zen").then(response => { this.setState({ quote: response.data});
});
}
render() {
return (
  <div>
    <p>{this.state.quote}</p>
</div>
}
}
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is ComponentDidUpdate()?

A

componentDidUpdate() is called when a re-render occurs due to new props or setState. React will call it everytime the component is updated. Not called first time something is rendered. Called after in every rerender.

Good for syncing up with any databse if something changes in the application. After it’s updated we can send the data off to be saved in the database.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is componentWillUnmount()

A

It’s the method called right before a component is destroyed or unmounted and basically removed from a page.

This is the place to do cleanup like invalidating timers, cancelling network request, removing event handlers directly put on DOM, cleaning up subscriptions.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly