useEffect: React's Power Hook

UseEffect Hook

  • The useEffect hook is one of the most commonly used hooks in ReactJS, used to handle side effects in functional components.
  • The useEffect in ReactJS is used to handle the side effects, such as fetching data and updating the DOM.
  • This hook runs on every render, but there is also a way to use a dependency array, which allows us to control the effect of rendering. 
  • Fetching data from an API.
  • Setting up a subscription.
  • Updating the DOM manually.
  • Starting or clearing timers.

Syntax of useEffect

useEffect(() => {
    // Code to run on each render
    return () => {
        // Cleanup function (optional)
    };
}, [dependencies]);
  • Effect function: This is where your side effect code runs.
  • Cleanup function: This optional return function cleans up side effects, such as subscriptions or timers, when the component is unmounted.
  • Dependencies array: React re-runs the effect if any of the values in this array change.

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

  • useEffect triggers a function on every component render, using React to execute specified tasks efficiently.
  • Positioned within the component, it grants easy access to state and props without additional coding.
  • For replicating lifecycle methods in functional components, copy and customize the provided code snippet according to your needs.

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?

  • useEffect runs once after the component mounts (because of the empty dependency array []).
  • It makes a GET request to https://jsonplaceholder.typicode.com/users.
  • The data is saved in state using. setUsers.
  • A The loading flag is used to show a loading message until the data is fetched.

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.