Skip to main content

UseEffect

The useEffect hook in React is used to perform side effects in functional components. It lets you run code after a component renders, similar to lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount in class components. This can include tasks like data fetching, subscriptions, or manually updating the DOM.

Syntax

useEffect(() => {
// Code to run on component mount or when dependencies change
return () => {
// Cleanup code, optional, runs when component unmounts or before re-running effect
};
}, [dependencies]);`
  • Effect function: Code inside useEffect that runs on mount, update, or unmount.
  • Cleanup function (optional): Runs when the component unmounts or when dependencies change, helpful for cleaning up subscriptions or timers.
  • Dependencies: Array that controls when the effect runs. If empty, it runs once on mount. If specified with variables, it runs when those variables change.

Example

Here's a simple example using useEffect to fetch data:

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

function DataFetcher() {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);

useEffect(() => {
// Effect function to fetch data when the component mounts
const fetchData = async () => {
setLoading(true);
const response = await fetch('https://api.example.com/data');
const result = await response.json();
setData(result);
setLoading(false);
};

fetchData();

// Optional cleanup function if needed, here it's not necessary
}, []); // Empty dependency array means this effect runs once on mount

if (loading) return <p>Loading...</p>;

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

export default DataFetcher;`

Explanation

  1. useEffect with Empty Dependency Array ([]): This effect runs once when the component mounts, ideal for initial data fetching.
  2. Fetching Data: The fetchData function fetches data and updates the state.
  3. Conditional Rendering: If loading is true, it shows a loading message; otherwise, it displays the fetched data.

Important Points

  • Cleanup: If the effect creates a subscription or a timer, return a cleanup function to unsubscribe or clear it when the component unmounts.
  • Dependencies Array: Specifies when the effect should re-run; if omitted, the effect runs after every render.