top of page

React useEffect Example

Writer's picture: CODING Z2MCODING Z2M

Updated: Jan 27

React useEffect Example

React useEffect Example

What is the useEffect Hook?

The useEffect hook in React is a built-in hook that allows you to perform side effects in functional components. Common use cases include fetching data, updating the DOM, and managing subscriptions.

Key Features:

  • Runs after the component renders (initially and/or on updates).

  • Can optionally clean up resources when the component unmounts.

  • Replaces lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount.

Syntax

useEffect(() => {
  // Code for side effect
  return () => {
    // Optional cleanup
  };
}, [dependencies]);
  • Effect function: The code to execute after rendering.

  • Cleanup function: Runs before the component unmounts or before running the effect again.

  • Dependencies array: Controls when the effect runs.


MERN Full Stack Web Development Training

Real-World Examples of useEffect (Fetching Data from an API)

In this React useEffect Example, Imagine an app that displays a list of users from an API.

import React, { useState, useEffect } from 'react';
function UserList() {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  useEffect(() => {
    // Fetching data
    const fetchUsers = async () => {
      const response = await fetch('https://jsonplaceholder.typicode.com/users');
      const data = await response.json();
      setUsers(data);
      setLoading(false);
    };
    fetchUsers();
  }, []); // Empty dependencies => run once after the initial render
  return (
    <div>
      {loading ? (
        <p>Loading...</p>
      ) : (
        <ul>
          {users.map((user) => (
            <li key={user.id}>{user.name}</li>
          ))}
        </ul>
      )}
    </div>
  );
}
export default UserList;

Explanation:

  • The API call is made after the component mounts (on the first render).

  • The users state is updated with the fetched data.



 Real-World Examples of useEffect (Updating the Page Title)

Imagine a to-do app that updates the page title with the number of pending tasks.

import React, { useState, useEffect } from 'react';
function TodoApp() {
  const [tasks, setTasks] = useState(['Task 1', 'Task 2']);
  useEffect(() => {
    // Update document title whenever tasks change
    document.title = `You have ${tasks.length} tasks`;
  }, [tasks]); // Dependency: Effect runs when 'tasks' changes
  return (
    <div>
      <h1>To-Do List</h1>
      <ul>
        {tasks.map((task, index) => (
          <li key={index}>{task}</li>
        ))}
      </ul>
      <button onClick={() => setTasks([...tasks, `Task ${tasks.length + 1}`])}>
        Add Task
      </button>
    </div>
  );
}
export default TodoApp;

Explanation:

  • The effect updates the page title whenever the tasks array changes.


MERN Full Stack Web Development Training

Common Patterns with useEffect

No Dependencies:

useEffect(() => { 
 console.log('Runs after every render');
});

Empty Dependencies:

useEffect(() => {
  console.log('Runs only once on mount');
}, []);

Specific Dependencies:

useEffect(() => {
  console.log('Runs only when count changes');
}, [count]);

Dependency Management: Specify the dependencies accurately to avoid unnecessary re-runs or stale data issues.


Conclusion

The useEffect hook is a powerful tool that helps manage side effects in React functional components. From fetching data to managing subscriptions or updating the DOM, useEffect allows developers to write cleaner, more efficient, and maintainable code. By following best practices and understanding dependencies, you can fully harness its potential.

Comments


bottom of page