React useEffect

Created By: chatGPT

useEffect is a hook in React that lets you perform side effects in function components. It can replace lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount. This makes it an essential tool for managing side effects such as data fetching, subscriptions, or manual DOM manipulation.The useEffect hook takes two arguments: a function that contains your side effect logic, and an optional dependency array. The dependency array determines when the effect should run.
Here’s a basic example of using useEffect to fetch data from an API:
import React, { useEffect, useState } from 'react';

const DataFetchingComponent = () => {
    const [data, setData] = useState(null);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        const fetchData = async () => {
            const response = await fetch('https://api.example.com/data');
            const result = await response.json();
            setData(result);
            setLoading(false);
        };

        fetchData();
    }, []); // Empty array means it only runs once after the first render

    if (loading) {
        return <div>Loading...</div>;
    }

    return <div>{JSON.stringify(data)}</div>;
};

export default DataFetchingComponent;
In this example, we define a state variable data to store the fetched data and a loading state to manage the loading status. The fetchData function is defined within useEffect, and it’s called immediately to fetch data when the component mounts.
To clean up any subscriptions or side effects, you can return a cleanup function from your effect. For example, if you were to set up a timer, you would clear it like this:
useEffect(() => {
    const timer = setTimeout(() => {
        console.log('Timer triggered');
    }, 1000);

    return () => clearTimeout(timer); // Cleanup
}, []);
It's important to note that if you include dependencies in the array, the effect will run again whenever any of those dependencies change. Here’s an example that listens for changes to a search term input:
const SearchComponent = () => {
    const [searchTerm, setSearchTerm] = useState('');

    useEffect(() => {
        console.log('Search term changed:', searchTerm);
    }, [searchTerm]); // Runs every time searchTerm changes

    return (
        <input
            type='text'
            value={searchTerm}
            onChange={e => setSearchTerm(e.target.value)}
        />
    );
};
useEffect is a powerful way to synchronize with the external environment while keeping your components declarative. By understanding its behavior and effective use of the dependency array, you can manage complex side effects in a clean and concise manner.
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