When you define a class component, you must always define a
render() method, as React calls it to find out what to render.
render() isn’t the only method that components can define!
When React instantiates a class component, it checks to see which lifecycle methods the class defines. You’ve already seen one of these: the
render() method. But the other lifecycle methods are optional; React only calls them if they’re defined. They include:
componentDidMount() — is called after the inital content has been rendered to the DOM.
componentDidUpdate(prevProps) — is called after subsequent updates are rendered to the DOM, and is passed the previous value of
componentWillUnmount() — is called before the component is removed from the DOM.
Lifecycle methods are useful for interacting with the “outside world” in response to changes in a React component. For example, you could define a
componentDidUpdate() method that changes your page’s background to a random color each time the form updates — no matter where the update comes from!
There’s one thing to be careful about when using
componentDidUpdate(). If you call
this.setState() inside it, then you’ll cause another update, and thus an infinite loop! You can use
this.setState(), but you should only do so inside an
if statement that prevents it from being called recursively.
In the real world, lifecycle methods are often used to call networking code as components are mounted, updated, and unmounted. For example, you could use a lifecycle method to automatically fetch data once your contact list app has loaded.
In fact, this sounds like a great exercise!
Your task is to fetch initial data using a lifecycle method.
Finishing this exercise off should only take a few lines of new code. If you get stuck, use a bit of trial and error before checking the solution — you should be able to make it work.
And once it does work, then you’re pretty much done. Like, actually done. Lifecycle methods are the final React feature we’ll cover in this course! But there are still some important loose ends to tie up, so click on through to the next lesson.