How To Use useEffect Hook In React? See Example

What Is useEffect Hook?

The useEffect hook allows functional components to perform side effects such as:

  • Fetching data
  • Updating the DOM
  • Subscribing to events
  • Timers and intervals

It replaces lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount.


Basic Syntax

useEffect(() => {
  // code to run
}, [dependencies]);
  • First argument → function containing side effect
  • Second argument → dependency array (controls when effect runs)

Example: Fetching Data

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

function Users() {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/users")
      .then(res => res.json())
      .then(data => setUsers(data));
  }, []); // empty array = run once on mount

  return (
    <ul>
      {users.map(user => <li key={user.id}>{user.name}</li>)}
    </ul>
  );
}

Example: Timer

function Timer() {
  const [seconds, setSeconds] = useState(0);

  useEffect(() => {
    const interval = setInterval(() => {
      setSeconds(s => s + 1);
    }, 1000);

    return () => clearInterval(interval); // cleanup
  }, []);

  return <h2>Seconds: {seconds}</h2>;
}

Tips for Using useEffect

  • Always clean up subscriptions or timers
  • Use dependency array carefully to avoid infinite loops
  • Multiple useEffect hooks can manage different side effects
  • Combine with useState for dynamic UI updates

Conclusion

The useEffect hook is essential for managing side effects in functional components, replacing most class component lifecycle methods.


Citations

https://savanka.com/category/learn/react/
https://www.w3schools.com/REACT/DEFAULT.ASP

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *