React components have a specific lifecycle, just like Angular and Vue.js ones.
In the case of class components, hooking into this lifecycle is, once again, simply a matter of implementing specific methods in your components.
Here's an example:
import React from 'react'; import ReactDOM from 'react-dom'; ... export class LifecycleAwareComponent extends React.Component { constructor(props) { super(props); ... } render() { ... } componentDidMount() { console.log('componentDidMount lifecycle hook called'); } ... }
In this example, we used the componentDidMount lifecycle hook, which is called as soon as the component's initialization is completed.
There are many other lifecycle hooks in React. Wojciech Maj (a member of the React community) created a great interactive diagram to visualize those. You can find it here: http://projects.wojtekmaj.pl/react-lifecycle-methods-diagram.
Here is the light version, listing only the most commonly used lifecycle hooks:
And here's a brief explanation of each of these:
Lifecycle hook function |
Description |
componentDidMount |
This lifecycle hook is invoked when the component has been instantiated and when its props and state have been initialized and rendered (usually in the DOM). Here, you can safely initiate network requests to load data, connect to a store (for example, Redux), and so on. |
componentDidUpdate |
With this lifecycle hook, you can react as soon as an update has been completed (for example, props or state have changed). Here, you can implement side-effects that should occur depending on the new values of your component. For example, you could initiate a new network request to fetch new data. This hook receives the previous props and state as an argument, which allows you to identify the exact changes that have occurred |
componentWillUnmount |
This hook is invoked when the component is about to be destroyed. Through this hook, you can clean things up. For example, you can use it to remove store subscriptions, cancel ongoing network requests, and so on. |
Let's look at event handling now.