useEffect Hook

23-Jan-2024

useEffect Hook

In React, the useEffect hook is employed to handle side effects within functional components. Side effects may include tasks such as data fetching, subscriptions, or manually interacting with the DOM.

What is the useEffect Hook?

The useEffect hook allows you to perform side effects in your functional components. It is executed after the component renders and can be used for tasks that don't necessarily belong to the component's render logic.

Example Usage:

import React, { useState, useEffect } from 'react'; const DataFetcher = () => { const [data, setData] = useState([]); // useEffect is used for data fetching useEffect(() => { const fetchData = async () => { try { 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(); }, []); // The empty dependency array ensures useEffect runs only once on component mount return ( <div> <h2>Data Fetcher</h2> <ul> {data.map((item) => ( <li key={item.id}>{item.name}</li> ))} </ul> </div> ); }; export default DataFetcher;

How It Works:

The useEffect hook is used to initiate asynchronous data fetching when the component mounts.

The fetchData function is defined inside useEffect to fetch data from an API.

The empty dependency array ([]) ensures that useEffect runs only once on component mount.

Once the data is fetched, the component state is updated, triggering a re-render.

Use Cases:

Data Fetching: Fetching data from APIs or external sources.

Subscriptions: Managing subscriptions or event listeners.

Manual DOM Manipulation: Making direct changes to the DOM.

The useEffect hook is an essential tool for handling side effects in React components, providing a clean and organized way to manage asynchronous tasks and interactions with the outside world.

Comments