React Grimoire
  • ⁉️Introduction
  • 🧑‍🎓🧑🎓 React Fundamentals
    • The Basic javascript "Hello world"
    • Basic view on React core API's
    • JSX
    • React Props and styling
    • Components
    • Handling Events With React
    • Form
    • Array and Lists
    • Class Component State
    • Class Component Life Cycle
    • PropTypes
  • 🪝React Hooks
    • Intro to hooks
    • useState
    • useEffect
    • useRef
    • useContext
    • useMemo
    • useCallback
    • useReducer
    • useLayoutEffect
    • useImperativeHandle
    • Hook flow
    • Custom hooks
      • useDebugValue
    • React 18 hooks
  • 📓React Guidelines
    • React Components Composition Guidelines
    • React hooks guidelines
    • The use of Memoization
    • Lifting State Up
  • 🔭Concepts
    • Advanced Patterns
      • Compound Components Pattern
      • Control Props Pattern
      • Props Getters Pattern
      • Custom hook pattern
      • Context Module
      • State Reducer
    • React Under the hood
      • 🏁What is "Rendering"?
      • 🏁React Lifecycle
      • 🏁Reconciliation & Virtual DOM in React
      • 🏁Fiber
    • ⏰Concepts to always have in mind
  • 🧩React ecosystem
    • Forms Tools
      • React Hook Form VS Formik
    • TypeScript
      • 🏁Conditional React props with TypeScript
    • 🏁Build tool choice for MVP projects
    • A CSS methodology comparison
      • 🏁Post CSS processor :Sass
      • 🏁CSS in js :Styled-components
      • 🏁Utility Classes: Tailwind
  • ⁉️Testing
    • In Progress
  • 🎭Performance
    • in Progress
  • 🚀Deployment
    • In Progress
  • 🖼️Design system
    • 🏁What's a design system anyway ?​?
  • 🔗Us-full links
    • Typescript and React basic tutorial
    • React-philosophies
    • React new doc
Powered by GitBook
On this page
  • componentDidMount( )
  • Class based:
  • Hooks:
  • componentDidUpdate( )
  • Class-based :
  • Hooks:
  • ComponentWillUnmount( )
  • Class based component:
  • Hooks:
  • Final Thoughts

Was this helpful?

Edit on GitHub
  1. Concepts
  2. React Under the hood

React Lifecycle

PreviousWhat is "Rendering"?NextReconciliation & Virtual DOM in React

Last updated 3 years ago

Was this helpful?

In React applications, code is separated into components to isolate different aspects of the user experience as well as the logic required to paint the user interface. These components define how the user should interact with the content and how they should see it.

Mounting, updating, and unmounting are the three main steps that each component goes through. You might conceive of it as component natural life cycle: they get born (mount), get to live (update), and get to die (unmount).

React components are generated by mounting them on the DOM, then changing them through updates, and lastly removing or unmounting them from the DOM. These three milestones are referred to as the React component lifecycle.

React Component may or may not go through all of the phases. Sometimes they aren't updated at all. They are never unmounted in other cases.

Without ever updating, a component can go through the mounting and unmounting phases back to back.)

The diagram above depicts the current React component lifecycle, along with the associated lifecycle functions. Specific lifecycle methods are provided by React and can be used to conduct specific tasks in different phases.

We'll try to demonstrate the most common and important life cycles by using a component-based and hooks component as an example.

Bear in mind that Hooks have another rendering flow , but in this section we will try to explain how they mimic the old lifecycles

if you want to see the new hook flow please see this link:

componentDidMount( )

We aren't actually defining DOM nodes with React even though we're defining virtual representations of nodes in our DOM tree.

Instead, we'll establish an in-memory view that React will manage and maintain.

When we talk about mounting, we're referring to the process of transforming virtual components into DOM elements that React can place in the DOM.

This method is usually called when the component has finished rendering for the first time. It is only called once throughout the lifecycle once after the component has finished mounting.

This is useful for things such as fetching data to populate the component.

Class based:

import React from "react";
class Component extends React.Component {  
    componentDidMount() {    
        console.log("Behavior before the component is added to the DOM");
    }   
    render() {    
        return <h1>Hello World</h1>;  
        }
    };

Hooks:

import React, { useEffect } from 'react';
const Component = () => {
  useEffect(() => {
    console.log('Behavior before the component is added to the DOM');
  }, []);  // Pass an empty array to run only callback on mount only. 
  return <h1>Hello World</h1>;
};

In the above example, When the component is mounted, the useEffect Hook is called.

The empty array [] in the second argument tells the useEffect Hook that it only has to run once, when the component is mounted.

componentDidUpdate( )

Before or after changing the actual rendering, we may wish to update some data in our component. Let's imagine we want to call a function to set up the rendering or to call a function when the props of a component change. The componentWillUpdate() method is an effective hook for preparing our component for a change

Throughout the app's lifecycle, this method is called several times. It is called as soon as the data has been updated. This method is not called for the initial render.

Class-based :

import React from 'react';
class Component extends React.Component {
  componentDidUpdate() {
    console.log('Behavior when the component receives new state or props.');
  }
  render() {
    return <h1>Hello World</h1>;
  }
}

Hooks:

As you can see if the below example the second argument in the hooks is blank meaning it will render every single time.

import React, { useEffect } from 'react';
const Component = () => {
  useEffect(() => {
    console.log('Behavior when the component receives new state or props.');
  });// No second argument, so run after every render.
  return <h1>Hello World</h1>;
};

But hold on a second. This seems to be much like how componentDidMount was implemented. So, what exactly is the difference? The most important thing to note is the absence of the optional second argument ([]). Every time the component is re-rendered, the Hook will be evaluated.

The optional second argument is an array of dependencies that will cause the useEffect Hook to be re-evaluated. It will only evaluate the Hook on mount if no values are provided in the array. If the array isn't provided, it will be evaluated every re-render. .

To elaborate on this a bit more — if we wanted to add a condition to componentDidUpdate we might do something like this in a class-based component:

This allows us to conditionally execute behavior based on the foo prop value changing. With Hooks, this becomes trivial:

class Component extends React.Component {
  componentDidUpdate(prevProps) {
    if (this.props.foo !== prevProps.foo) {
      console.log("Behavior when the value of 'foo' changes.");
    }
  }
  render() {
    return <h1>Hello World</h1>;
  }
}
import React, { useEffect } from 'react';
const Component = ({ foo }) => {
  useEffect(() => {
    console.log("Behavior when the value of 'foo' changes.");
  }, [foo]);
  return <h1>Hello World</h1>;
};

The useEffect Hook will now only be evaluated if the value of foo changes since it is included in the option dependency array.

ComponentWillUnmount( )

This method will be called when the component is unmounted, as the name implies, and it will only be called once during the component's lifecycle. This is where we take care of any cleanup tasks, such as clearing timeouts, cleaning data, disconnecting websockets, and so on.

Before the component is unmounted, React will call out to the componentWillUnmount() callback.

Class based component:

import React from 'react';
class Component extends React.Component {
  componentWillUnmount() {
    console.log('Behavior right before the component is removed from the DOM.');
  }
  render() {
    return <h1>Hello World</h1>;
  }
}

Hooks:

import React, { useEffect } from 'react';
const Component = () => {
  useEffect(() => {
    return () => {
      console.log('Behavior right before the component is removed from the DOM.');
    };// It will be called before unmounting.
  }, []);
  return <h1>Hello World</h1>;
};tsx

Just hang on a minute longer! This seems to be even more similar to how componentDidMount was handled! In reality, they're fairly similar. The return statement inside the useEffect function body is the only difference. If useEffect returns a function, that function is only called after the component is removed from the DOM.

Final Thoughts

No Lifecycle method replacement

Below are some of the methods that do not have any lifecycle method replacement for hooks according to the react documentation:

  1. componentDidCatch ( )

  2. getSnapshotBeforeUpdate( )

  3. getDerivedStateFromError ( )

Why Hooks? / Why not Classes?

The class components are long and winding. To create a 'effect logic,' we are frequently obliged to duplicate our logic in different lifecycle functions.

Class components do not provide an easy method for sharing logic between components (HOC and friends do not provide an elegant solution) — React Hooks, on the other hand, allow us to create our custom hooks. a much simpler solution.

Other then that the use of this add a lot of complexity and reduce readability of the code

i have stumble upon one of Kent C Dodds articles that clarify more the complexity of the class components use.

I truly recommend to have an eye on Kent C Dodds blog , it's a rich maybe the richest resources for React and JavaScript topics.

There are other life cycle for a react component, even new one are emerging as the getDerivedStateFromProps as of designed to replace componentWillReceiveProps. and it's invoked right before calling the render method, both on the initial mount and on subsequent updates. It should return an object to update the state, or null to update nothing.

🔭
🏁
React 17
React Lifecycle Methods diagram
Credits : Wojciech Maj
GitHub - donavon/hook-flow: A flowchart that explains the new lifecycle of a Hooks component. https://dwe.st/hfGitHub
React hooks lifecycle diagram
Hooks FAQ – React
Hooks FAQ – React
Classes, Complexity, and Functional Programmingkentcdodds
The Kent C. Dodds Blogkentcdodds
https://github.com/Wavez/react-hooks-lifecycle
https://github.com/donavon/hook-flow
Logo
Logo
Logo
Logo
Logo
Logo