UseEffect Hook

Syntax of useEffect

useEffect(() => {
    // Code to run on each render
    return () => {
        // Cleanup function (optional)
    };
}, [dependencies]);

Examples of useEffect Usage

  1. App.jsx
    
    import React from "react";
    import "./App.css";
    import Counter from "./components/Counter";
    
    function App() {
        return (
            <div className="App">
                <HookCounterOne />
            </div>
        );
    }
    export default App;
  2. Counter.jsx
    
    import { useState, useEffect } from "react";
    
    function Counter() {
        const [count, setCount] = useState(0);
    
        useEffect(() => {
            document.title = `You clicked ${count} times`;
        }, [count]);
    
        return (
            <div>
                <button onClick={() => setCount((prevCount) => prevCount + 1)}>
                    Click {count} times{" "}
                </button>
            </div>
        );
    }
    export default Counter;

In this example

Controlling side effects in useEffect

  1. To run useEffect on every render, do not pass any dependencies.
    useEffect(()->{
        // Example Code
    })
  2. To run useEffect only once on the first render, pass an empty array in the dependency.
    useEffect(()->{
        // Example Code
    }, [] )
  3. To run useEffect on the change of a particular value. Pass the state and props in the dependency array.
    useEffect(()->{
        // Example Code
    }, [props, state] )

Lifecycle methods using the useEffect hook

The useEffect() hook is not only used for handling side effects, but it also allows functional components to replicate the behavior of class-based lifecycle methods.

  1. componentDidMount
  2. componentDidUpdate
  3. componentwillUnmount

Example. Fetching Data with useEffect

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

const UserList = () => {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/users')
      .then((response) => response.json())
      .then((data) => {
        setUsers(data);
        setLoading(false);
      })
      .catch((error) => {
        console.error('Error fetching users:', error);
        setLoading(false);
      });
  }, []); 

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

  return (
    <div>
      <h2>User List</h2>
      <ul className="list-disc pl-5">
        {users.map((user) => (
          <li key={user.id}>
            {user.name} - <span className="text-sm text-gray-600">{user.email}</span>
          </li>
        ))}
      </ul>
    </div>
  );
};

export default UserList;

How does it work?

Final Thought

useEffect is a powerful hook that replaces lifecycle methods in React function components. When used correctly, it makes your components clean, reactive, and side-effect-safe. Understanding its timing and dependencies is key to writing optimal React code.