React lifecycle methods

Created By: chatGPT

In React, lifecycle methods are hooks that allow you to run code at specific points in a component's life. These methods can be categorized into three phases: Mounting, Updating, and Unmounting. Each phase contains several methods that provide control over the component's behavior, such as fetching data, subscribing to events, or cleaning up resources.
class MyComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = { data: null }; 
    }

    componentDidMount() {
        // Called after the component is mounted
        this.fetchData();
    }

    componentDidUpdate(prevProps, prevState) {
        // Called after updates are made
        if (this.state.data !== prevState.data) {
            this.processData();
        }
    }

    componentWillUnmount() {
        // Cleanup any subscriptions or listeners
        this.cleanup();
    }

    fetchData() {
        // Assume fetch function retrieves data
    }

    processData() {
        // Logic to process the fetched data
    }

    cleanup() {
        // Cleanup logic here
    }

    render() {
        return <div>{this.state.data}</div>;
    }
}

Each method has a specific role:

  • componentDidMount: Invoked immediately after a component is mounted. Useful for API calls or subscriptions.
  • componentDidUpdate: Invoked immediately after updating. Useful for responding to prop or state changes.
  • componentWillUnmount: Invoked just before a component is unmounted. Ideal for clean-up code to prevent memory leaks.
class ExampleComponent extends React.Component {
    componentDidMount() {
        // Example API call
        fetch('/api/data')
            .then(response => response.json())
            .then(data => this.setState({ data }));
    }

    componentDidUpdate(prevProps) {
        if (this.props.id !== prevProps.id) {
            // Handle id change
            this.fetchData();
        }
    }

    componentWillUnmount() {
        // Clean up API connection
        this.cleanupConnection();
    }

    render() {
        return <div>{this.state.data}</div>;
    }
}
React hooks like useEffect can be seen as an alternative to lifecycle methods in functional components. Hooks allow you to manage side effects directly in functional components without needing class-based lifecycle methods.
import React, { useEffect, useState } from 'react';

const FunctionalComponent = () => {
    const [data, setData] = useState(null);

    useEffect(() => {
        // Simulate componentDidMount
        fetch('/api/data')
            .then(response => response.json())
            .then(setData);

        // Simulate componentWillUnmount
        return () => {
            console.log('Cleanup');
        };
    }, []); // Empty array ensures this runs once

    return <div>{data}</div>;
};
Introduction And SetupComponentsPropsStateLifecycle MethodsHooksContext APIJsx SyntaxVirtual DomEvent HandlingFormsRoutingPerformance OptimizationError BoundariesHigher Order ComponentsRender PropsPortalsFragmentsRefsControlled ComponentsUncontrolled ComponentsMemoizationSuspenseLazy LoadingProp TypesDefault PropsConditional RenderingList And KeysAccessibility (a11y)State ManagementTestingCustom HooksUseEffectUseStateUseContextUseReducerUseMemoUseCallbackUseRefUseLayoutEffectUseImperativeHandleUseDebugValueAutomatic BatchingSuspense For Data FetchingStrict ModeForward RefsCreateContextLazyUseTransitionUseDeferredValueUseId