How to Achieve React Lifecycle Methods in Functional Components using useEffect

Dev Balaji
2 min readApr 25, 2023

--

In React, functional components are used for writing components that are mainly responsible for rendering the UI based on the input props. However, functional components don’t have access to the React lifecycle methods like class components do.

To achieve similar functionality, React introduced a hook called useEffect. useEffect is used to handle side effects in functional components. Side effects refer to any change in the state, props, or UI that is caused by the component other than rendering.

Here is how you can replace the class component lifecycle methods with useEffect in functional components:

1. ComponentDidMount

The componentDidMount lifecycle method is called once after the component is mounted. To achieve the same effect using useEffect, you can pass an empty array [] as the second argument to useEffect. This tells React to run the effect only once when the component is mounted.

Example:

useEffect(() => {
// code to be executed once when component mounts
}, []);

2. ComponentDidUpdate

The componentDidUpdate lifecycle method is called whenever the component updates. To achieve the same effect using useEffect, you can pass the state or props that you want to watch for changes as the second argument to useEffect.

Example:

useEffect(() => {
// code to be executed whenever state or props change
}, [state, prop]);

3. ComponentWillUnmount

The componentWillUnmount lifecycle method is called just before the component is unmounted. To achieve the same effect using useEffect, you can return a cleanup function from the effect function.

Example:

useEffect(() => {
// code to be executed when component mounts
return () => {
// code to be executed when component unmounts
};
}, []);

4. ComponentWillMount

The componentWillMount lifecycle method is similar to componentDidMount but is called just before the component mounts. There is no direct replacement for this method in useEffect, but you can achieve the same effect by using the useLayoutEffect hook.

Example:

useLayoutEffect(() => {
// code to be executed just before component mounts
}, []);

In conclusion, useEffect is a powerful hook that allows us to handle side effects in functional components. By using useEffect, we can achieve similar functionality as class components with lifecycle methods.

--

--

Dev Balaji
Dev Balaji

Written by Dev Balaji

🚀 Tech Enthusiast | 🌟 Mastering JavaScript & Frameworks | 💡 Sharing Tips & Tricks | 📘 Aspiring Blogger & Architect | 🐍 Python Practitioner

No responses yet