What are React Lifecycle Methods?

By Prajwal Haniya

Tech-letter #11 | February 28, 2023

Class components don’t have hooks they have lifecycle methods instead.

You can think of React lifecycle methods as the series of events that happen from the birth of a React component to its death.

You cannot modify the component state within the render()

In React class components, the render method itself shouldn’t cause side effects. It would be too early — we typically want to perform our effects after React has updated the DOM. This is why in React classes, we put side effects into componentDidMount and componentDidUpdate .

componentDidMount():

componentDidMount() is called as soon as the component is mounted and ready. This is a good place to initiate API calls if you need to load data from a remote endpoint.

componentDidMount() {
    fetch(url)
    .then(resp => resp.json())
    .then(data => this.setState())
}

This is different in the functional components. In the functional component, you can make use of the hook useEffect().

useEffect(() => {
    fetch(url)
     .then(resp => resp.json())
     .then(data => this.setState()
    }, [])

Passing [] as the second argument, useEffect to behave like componentDidMount as this tells useEffect that your effect isn’t dependent on any values from props or state thus never re-running. By default useEffect() would run on every update on the component but by passing an array of dependencies, in this case, no dependencies so it never runs again.

componentDidUpdate():

This lifecycle method is invoked as soon as the updating happens. The most common use case for the componentDidUpdate() method is updating the DOM in response to prop or state changes. This is one of the most used built-in methods, which is not called for the initial render nor applicable to your functional details.

using the componentDidUpdate() in the functional component

If you don’t pass any dependency, the useEffect Hook will still work as the componentDidUpdate lifecycle method. On the initial mount of the component, useEffect runs the callback function without checking if the dependency has changed or not.

componentWillUnmount():

This lifecycle method is called just before the component is unmounted and destroyed. If there are any cleanup actions that you would need to do, this would be the right spot.

The only thing that we need to do is to return a function inside the callback function of the useEffect Hook

useEffect(() => {
  window.addEventListener("mousemove", () => {});
  return () => {
    window.removeEventListener("mousemove", () => {})
  }
}, []);

Resources:

React: class components vs function components

React Lifecycle Methods - A Deep Dive - Programming with Mosh

Using React’s useEffect Hook with lifecycle methods - LogRocket Blog

States and componentDidMount() in functional components with Hooks.