Loading...

What's the use of useEffect hook in React?

question react front-end
Ram Patra Published on February 2, 2024

In React, the useEffect hook is used to perform side effects in functional components. Side effects can include data fetching, subscriptions, manual DOM manipulations, and other operations that cannot be handled during the render phase.

The useEffect hook is called after the component has rendered, and it runs the specified function (the effect) that can contain code with side effects. Here’s a basic example to illustrate its usage:

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

function ExampleComponent() {
  // State to store data fetched from an API
  const [data, setData] = useState(null);

  // useEffect hook to fetch data when the component mounts
  useEffect(() => {
    const fetchData = async () => {
      try {
        // Simulating an API call
        const response = await fetch('https://api.example.com/data');
        const result = await response.json();
        setData(result);
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    };

    fetchData(); // Call the function to fetch data

    // Cleanup function (optional): will be called when the component unmounts
    return () => {
      // Perform cleanup, unsubscribe, etc.
    };
  }, []); // Empty dependency array means the effect runs only once after the initial render

  return (
    <div>
      {/* Render component using the fetched data */}
      {data ? <p>Data: {data}</p> : <p>Loading...</p>}
    </div>
  );
}

export default ExampleComponent;

In this example:

  • The useEffect hook is used to fetch data from an API after the component has mounted.
  • The function passed to useEffect is the effect itself.
  • The empty dependency array ([]) means that the effect runs only once after the initial render. If you provide dependencies, the effect will run whenever those dependencies change.

Key points about useEffect:

  1. Side Effects: It is primarily used for handling side effects in functional components, where side effects might include data fetching, subscriptions, or manual DOM manipulations.
  2. Asynchronous Operations: You can perform asynchronous operations inside the useEffect function, such as fetching data using async/await.
  3. Cleanup: If your effect involves any cleanup (e.g., clearing intervals, unsubscribing from subscriptions), you can return a cleanup function from the useEffect.
  4. Dependency Array: By providing a dependency array, you can control when the effect runs. If the array is empty, the effect runs once after the initial render. If dependencies are specified, the effect runs whenever those dependencies change.

useEffect is a crucial tool for managing side effects in React functional components, contributing to better organization and lifecycle management.

Presentify

Take your presentation to the next level.

FaceScreen

Put your face and name on your screen.

ToDoBar

Your to-dos on your menu bar.

Ram Patra Published on February 2, 2024
Image placeholder

Keep reading

If this article was helpful, others might be too

question typescript react September 28, 2024 How to add a custom element to a Next.js/Typescript project?

Let’s say I have a custom element setapp-badge that I want to use in my tsx files. If I go ahead and use it, the compiler will throw an error and Next.js will fail to build. It seems the problem might be a combination of how Next.js, TypeScript, and custom elements work together. Therefore, let’s try an approach that avoids the namespace/module issues while ensuring custom elements are recognized in a Next.js/TypeScript project.

question react front-end February 19, 2024 How to smoothly scroll to a specific content or element in React?

To implement scrolling to a specific content or element on click in a React application, you can follow these steps:

question nextjs react February 9, 2024 Main advantages of using the Link component in Next.js over Anchors and Buttons

The main advantage of using the Link component in Next.js for client-side navigation is its optimized prefetching behavior, which enhances the performance and user experience of your web application. Here’s a breakdown of the key advantages: