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.

Javascript




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:

  • Adapt the code to your specific use cases.
  • Be mindful of dependency array optimization to avoid unnecessary re-renders.
  • Use the cleanup function responsibly to prevent memory leaks or other issues.

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

Javascript




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



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.

Similar Reads

Approach to manage Effects with useEffect Hook:

Before useEffect, managing side effects in functional components was cumbersome, and often required class components or external libraries. The useEffect offers a concise and integrated solution: Declarative Nature: You describe the desired side effect, and React takes care of the when and how, simplifying your code. Lifecycle Integration: Execute effects at specific stages of a component’s lifecycle, like componentDidMount or componentWillUnmount, for granular control. Dependency Array: Fine-tune when the effect re-runs by specifying the values it relies on. This optimizes performance by preventing unnecessary re-renders. Cleanup Function: Like a responsible citizen, clean up after yourself! This optional function allows you to release resources acquired in the effect, preventing memory leaks or other issues....

Steps to Create React Application:

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

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....

Contact Us