Open In App

Effect Management with useEffect Hook in React

useEffect serves as a foundational tool in React development, enabling developers to orchestrate side effects within functional components systematically. It facilitates the management of asynchronous tasks, such as data fetching and DOM manipulation, enhancing code organization and maintainability. By defining when these side effects should occur, useEffect promotes a structured approach to development, leading to more robust and scalable applications.

Approach to manage Effects with useEffect Hook:

Importing useEffect Hook in React:

To utilize useEffect , import it from the react library at the top of your component file.



import React, { useEffect } from 'react';

Syntax of useEffect Hook:

Within your functional component, call useEffect with the effect function and an array of dependencies as arguments.

useEffect(() => {
// Your effect function here
}, [dependencies]);

Steps to Create React Application:

Step 1: Create a react application using the following command.



npx create-react-application my-react-app

Step 2: Naviate to the root directory of your application using the following command.

cd my-react-app

Example of useEffect Hook for Effect Management:

Example 1: Fetching Data: This React component fetches data from an API when it’s first shown on the screen. It then displays the fetched data or a loading message while waiting.




import React,
{
    useState,
    useEffect
} from 'react';
 
function MyComponent() {
    const [data, setData] = useState(null);
 
    useEffect(
        () => {
            fetch('https://jsonplaceholder.typicode.com/albums/1')
                .then(response => response.json())
                .then(data => setData(data));
        }, []
    ); // No dependencies, run only on mount
 
    return (
        <div>
            {
                data ?
                    <p>Data: {JSON.stringify(data)}</p> :
                    <p>Loading...</p>
            }
        </div>
    );
}
 
export default MyComponent;

Step to start the Application:

npm start

Output:

output 1

Example 2: Setting Up and Cleaning Up Timers:

By effectively mastering useEffect, you can create well-structured, maintainable, and performant React applications that manage side effects gracefully.




import React,
{
    useState,
    useEffect
} from 'react';
 
function MyComponent() {
    const [count, setCount] = useState(0);
 
    useEffect(() => {
        const intervalId =
            setInterval(
                () => setCount(count + 1), 1000);
 
        // Cleanup function
        return () => clearInterval(intervalId);
    }, []);
    // No dependencies, run only on mount
 
    return (
        <div>
            <p>
                Count: {count}
            </p>
        </div>
    );
}
 
export default MyComponent;

Step to start the Application:

npm start

Output:

output


Article Tags :