Component Lifecycle in React

alter80

Fahim Hossain

Posted on December 22, 2021

Component Lifecycle in React

*ReactJS * works by using components. It makes the code more reusable. These components have a specific lifecycle where they get life and work on the code then it goes into hibernation. Before starting about the component lifecycle, we need to know what is component in ReactJS?

A component is a block of a react app. Multiple components are basically blocks of the react app having a specific HTML render output in it. So we can say the starting component is App.js in the prebuilt react file. Which can be connected with the other components for routing or building the site more dynamic and useful.

Image description
Functional and Class components are two types of components written in React, we will talk about functional components. The above image represents a functional component where a function is having a return output. This function is exportable, which means we can use this component anywhere in the react app and the function will print the line written under

wrapper. If anyone needs to use multiple divs in a single element, then he/she can use multiple div tags under the main div tag.

So this is somewhat an idea about components and what a component really is in ReactJS. But we were talking about the component lifecycle. These components work in a cycle where it maintains 3 steps. They are:

  1. Mounting
  2. Updating and
  3. Unmounting

Image description
(source: https://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/)

1. Mounting
In this phase of react component its being initialised by using constructors. These constructors are simple functions or methods having the state of the variables. Though this constructor applies on class based components because in Functional components it uses “useState” hook for setting and changing the state in a variable.
So mostly the hook is there to handle these constructors. From the Q&A section of react it says:

Image description

Anyways, so in this phase the component mounts in the DOM using a default state. In the functional component the code will be similar like this.

const App = () => {
  const [counter, setCounter] = useState(0);

  console.log("This happens on EVERY render.");
  return (
    <>
      <div>Counter: {counter}</div>
      <div style={{ marginTop: 20 }}>
        <button onClick={() => setCounter(counter + 1)}>Increment</button>
      </div>
    </>
  );
};
Enter fullscreen mode Exit fullscreen mode

[credit: https://dev.to/bytebodger/constructors-in-functional-components-with-hooks-280m ]

In the above code the useState hook mounts the variable to the dom and after that it will prepare itself for updating phase.

componentDidMount() is invoked immediately after a component is mounted (inserted into the tree).

2. Updating
Updating happens when an existing dom is being changed or manipulated. These updates can be handled by state or props. From the above we somehow got a glimpse of state. But props is a value which is passed by another component. It's a read only property which is received like an argument in functional components. If we update the code by setting a new state the code will be like this:

const App = () => {
  const [counter, setCounter] = useState(0);

  //new state update
  setCounter(5);


  return (
    <>
      <div>Counter: {counter}</div>
      <div style={{ marginTop: 20 }}>
        <button onClick={() => setCounter(counter + 1)}>Increment</button>
      </div>
    </>
  );
};
Enter fullscreen mode Exit fullscreen mode

From the above code, I’ve set the new setCounter value to 5 so the code will start counting from 5 instead of 0. Also the onClick function is updating the state on every click.

If the variable or the state is changed then the render function happens. Before that the updating process keeps going on.
componentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render.

3. Unmounting
The component will unmounts when the component is being removed from the DOM. componentWillUnmount() is invoked immediately before a component is unmounted and destroyed. Perform any necessary cleanup in this method, such as invalidating timers, cancelling network requests, or cleaning up any subscriptions that were created in componentDidMount().

Though in react documentation it's clearly said that, “You should not call setState() in componentWillUnmount() because the component will never be re-rendered. Once a component instance is unmounted, it will never be mounted again.”

Representation of react component lifecycle:

Image description

💖 💪 🙅 🚩
alter80
Fahim Hossain

Posted on December 22, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

What was your win this week?
weeklyretro What was your win this week?

November 29, 2024

Where GitOps Meets ClickOps
devops Where GitOps Meets ClickOps

November 29, 2024

How to Use KitOps with MLflow
beginners How to Use KitOps with MLflow

November 29, 2024

Modern C++ for LeetCode 🧑‍💻🚀
leetcode Modern C++ for LeetCode 🧑‍💻🚀

November 29, 2024