
React Lifecycle Methods Using Class & Functional Components
15 August, 2023
1
1
0
Contributors
React lifecycle methods are functions that are called at different stages of a component's lifecycle. These methods allow you to perform actions at specific points in the component's creation, update, and destruction process. With the introduction of React Hooks, functional components can also achieve similar behavior to class components. Let's explore both class and functional component approaches to lifecycle methods.
Class Components:
In class components, you can utilize various lifecycle methods. Here are some of the main ones:
1.Mounting Phase:
◻ constructor(): Initializes state and binds event handlers.
◻ componentDidMount(): Called after the component is mounted in the DOM. Ideal for initiating API calls or subscriptions.
2. Updating Phase:
◻ shouldComponentUpdate(nextProps, nextState): Decides whether the component should re-render based on changes in props or state.
◻ componentDidUpdate(prevProps, prevState): Called after a component update. Useful for side effects after a re-render.
3. Unmounting Phase:
◻ componentWillUnmount(): Invoked before a component is unmounted. Used for cleanup tasks like unsubscribing or removing event listeners.
Functional Components with Hooks:
Functional components use hooks to achieve similar behavior. Some relevant hooks include:
1. State and Side Effects:
◻ useState(): Manages state in functional components.
◻ useEffect(): Mimics componentDidMount, componentDidUpdate, and componentWillUnmount combined.
2. Conditional Rendering:
◻useMemo(): Memoizes expensive computations.
◻ useCallback(): Memoizes callback functions.
3. Context and Reducers:
◻ useContext(): Accesses context in a functional component.
useReducer(): Manages complex state logic with a reducer function.
Here's an example of how a functional component using hooks might mimic the lifecycle behavior of a class component:
import React, { useState, useEffect } from 'react';
function FunctionalComponent() {
const [data, setData] = useState([]);
useEffect(() => {
// This is equivalent to componentDidMount and componentDidUpdate
fetchData();
return () => {
// This is equivalent to componentWillUnmount
cleanup();
};
}, []);
return (
<div>
{/* Render component */}
</div>
);
}