useEffect in react js

useEffect is a React Hook that is used to synchronize a component with external system or we can say that useEffect allow to perform some side effect in the component eg: updating the DOM, fetching the data. We can call useEffect at the top of the component as it is a hook so we can’t call it inside loop or any condition, we can use multiple useEffect in same component.

Syntax

import React, { useEffect } from 'react';

const Componentname = () => {
    useEffect(() => {
        // Code to run when the component mounts

        return () => {
            // Cleanup code runs when the component unmounts
        };
    }, []); // Dependency array, controls when the effect runs

    return (
        <div>
            {/* JSX */}
        </div>
    );
};

export default Componentname ;



Concept:

a) Effect Function: First argument to useEffect is a function which contain side effect you want to perform, its run after the component render.

b) Cleanup Function: Cleanup function is returned by ‘useEffect’, it is optional which execute when the component unmounts.

c) Dependency Array: The dependency array is an secondary argument that control when the effect run. If we pass empty array [] then the effect will run once only at the initial time. Or if we provide variables in the array, effect will run whenever those variables got changes.

Example:

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

const CounterComponent = () => {
    const [count, setCount] = useState(0);

    useEffect(() => {
        console.log(`Count changed to: ${count}`);

        return () => {
            console.log(`Cleanup count: ${count}`);
        };
    }, [count]); // Effect runs whenever 'count' changes

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

export default CounterComponent;

useEffect with API:

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

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

    useEffect(() => {
        const fetchData = async () => {
            const response = await fetch('https://apiurl.com');
            const result = await response.json();
            setData(result);
        };

        fetchData();
    }, []); // Empty array to run this effect only on mount

    return (
        <div>
            <h1>Fetched Data:</h1>
            <pre>{JSON.stringify(data, null, 2)}</pre>
        </div>
    );
};

export default apiFetchingComponent;

useEffect with dependency

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

const MyComponent = () => {
    const [count, setCount] = useState(0);

    useEffect(() => {
        console.log(`Count has changed to: ${count}`);

        return () => {
            console.log(`Cleanup for count: ${count}`);
        };
    }, [count]); // Effect runs whenever 'count' changes

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

export default MyComponent;

Keep Learning 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *