React Hook Lifecycles: Simplified Explanation with Practical Code Examples

Amir Moradnejad
5 min readSep 20, 2023

--

Level UP In React Lifecycles

Exploring the React Component Lifecycle

The React component lifecycle is a fundamental concept that defines the journey of a React component from its creation to its eventual destruction. React functional component lifecycle encompasses three core stages:

  1. Mounting: The journey begins when a component is first created and then seamlessly inserted into the Document Object Model (DOM). During this phase, developers have the opportunity to carry out tasks like data retrieval and event listener setup.
  2. Updating: As the journey progresses, we encounter the updating phase. Here, the component is re-rendered in response to changes in its props or state. This phase is vital for updating the user interface or executing actions based on the updated data.
  3. Unmounting: Our journey concludes with the unmounting phase, marking the graceful departure of the component from the DOM. It is crucial during this phase to meticulously manage resources, such as event listeners, to prevent memory leaks.

In each of these lifecycle phases, developers wield a unique set of methods, allowing them to execute precise tasks and efficiently govern their component’s behavior. A profound comprehension of these phases is essential for adeptly navigating React components and ensuring the seamless operation of your applications.

let’s dive into the lifecycle in react hooks

how to use lifecycle methods in functional react components?

In the following section, we’ll explore every stage of the React component lifecycle and show how to recreate them using the useEffect Hook. Plus, we’ll offer practical examples for each stage.

1. Component Mounting lifecycle in react hooks

The mounting phase, is the component’s inception. Using the useEffect Hook with an empty dependency array ([]), we emulate this phase in functional components. This is where we conduct tasks like data fetching and event listener setup. this is an example code of component mount with useEffect:

import React, { useEffect } from 'react';

function MountingExample() {
useEffect(() => {
// Code here runs after the component is mounted.
// You can perform data fetching or set up event listeners here.
return () => {
// Clean up code (equivalent to componentWillUnmount).
};
}, []);

return <div>Component Mounted!</div>;
}

2. Component Updating lifecycle in react hooks

When a component’s props or state change, it may need to update its UI or perform other actions. With useEffect, we achieve this by specifying dependencies, which trigger the effect whenever those dependencies change. an example code of component updating with useEffect hook:

import React, { useState, useEffect } from 'react';

function UpdatingExample() {
const [count, setCount] = useState(0);

useEffect(() => {
// Code here runs whenever 'count' changes.
// You can perform actions based on the updated state.
document.title = `Count: ${count}`;
}, [count]);

return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}

3. Component Unmounting lifecycle in react hooks

When a component is removed from the DOM, it’s crucial to clean up resources like event listeners to avoid memory leaks. The useEffect Hook can handle this by returning a cleanup function.

import React, { useState, useEffect } from 'react';

function UnmountingExample() {
const [visible, setVisible] = useState(true);

useEffect(() => {
// Code here runs after the component is mounted.
const handleClick = () => console.log('Clicked!');

document.addEventListener('click', handleClick);

return () => {
// Clean up code (equivalent to componentWillUnmount).
document.removeEventListener('click', handleClick);
};
}, []);

return (
<div>
<button onClick={() => setVisible(!visible)}>Toggle Component</button>
{visible && <p>Click anywhere to see the effect!</p>}
</div>
);
}

Understanding useEffect Behavior in Plain Terms:

If useEffect has a dependency array (the second argument), it will run the code inside it when the component updates. The code will execute after the initial render and after any subsequent updates where the dependencies have changed.

If useEffect has no dependencies but includes a cleanup function (a return statement), it will run the cleanup code when the component unmounts. This is essentially equivalent to the componentWillUnmount lifecycle method in class components.

If useEffect has no dependencies and no return statement, it will run the code inside it only when the component mounts. It won’t run on updates or unmount.

So, to summarize:

Dependency array in useEffect:
Code runs on component updates.
Cleanup function in useEffect with an empty dependency array:
Code runs on component unmount.
No dependency array and no cleanup function:
Code runs on component mount and not on updates or unmount.

React Class Component Lifecycle with example code

In class-based components, you have access to a set of predefined lifecycle methods: componentDidMount: Executes after the component has been inserted into the DOM. It’s suitable for tasks like data fetching and setting up event listeners.

componentDidMount:

Executes after the component has been inserted into the DOM. It’s suitable for tasks like data fetching and setting up event listeners.

lass ClassComponent extends React.Component {
componentDidMount() {
// Code here runs after the component is mounted.
}

// ... Other lifecycle methods
}

componentDidUpdate:

Invoked after a component updates due to changes in props or state. It’s used for tasks that should occur when the component’s data or UI changes.

class ClassComponent extends React.Component {
componentDidUpdate(prevProps, prevState) {
// Code here runs after a component update.
}

// ... Other lifecycle methods
}

componentWillUnmount:

Called before a component is removed from the DOM. It’s essential for cleaning up resources like event listeners.

class ClassComponent extends React.Component {
componentWillUnmount() {
// Code here runs before the component unmounts.
}

// ... Other lifecycle methods
}

Conclusion of react hook lifecycles

In this article, we explored the React component lifecycle and learned how to manage it effectively using the useEffect Hook. We covered the mounting, updating, and unmounting phases, along with important insights about useEffect.

We also compared class component lifecycles with Hook-based lifecycles, showcasing the benefits of Hooks in modern React development.

This knowledge equips you to write practical and useful code to handle React lifecycles confidently, regardless of whether you’re working with class components or Hooks. React component lifecycles are crucial for building robust applications, and you’re now well-prepared to utilize them in your projects.

Happy coding!

--

--