A complete guide to the useEffect React Hook

React’s useEffect hook is a powerful tool for handling side effects in your functional components. It allows you to perform tasks like fetching data, updating the DOM, or subscribing to external events. In this blog post, we’ll explore how to use useEffect with a real-world example using the REST API.

What is useEffect?

useEffect is a hook in React that enables the execution of side effects in functional components. Side effects can include data fetching, subscriptions, or manually changing the DOM.

Here is a basic syntax of useEffect:

import { useEffect } from 'react';

function ExampleComponent() {
  useEffect(() => {
    // Side effect code goes here
    return () => {
      // Cleanup code (optional)
    };
  }, [/* dependency array */]);

  // Component rendering code
}

Fetching Data with useEffect

Let’s create a simple React component that fetches and displays data from the JSONPlaceholder API using the Fetch API.

Step 1: Create a Component

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

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

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch('https://jsonplaceholder.typicode.com/users');
        const data = await response.json();
        setUsers(data);
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    };

    fetchData();
  }, []); // Empty dependency array means this effect runs once on mount

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

export default UserList;

In this example, we define a UserList component that fetches user data from the JSONPlaceholder API when the component mounts using the Fetch API.

Step 2: Implement Dependency

In certain scenarios, you might need to re-run the effect when a particular dependency changes. For instance, if you want to refetch data when a specific prop or state value changes.

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

function UserDetails({ userId }) {
  const [user, setUser] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`);
        const data = await response.json();
        setUser(data);
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    };

    fetchData();
  }, [userId]); // Re-run effect when userId changes

  if (!user) {
    return <p>Loading...</p>;
  }

  return (
    <div>
      <h2>User Details</h2>
      <p>Name: {user.name}</p>
      <p>Email: {user.email}</p>
      {/* Additional user details */}
    </div>
  );
}

export default UserDetails;

Now, the UserDetails component takes a userId prop, and the useEffect will re-run whenever the userId prop changes.

Conclusion

useEffect is a crucial tool in React for managing side effects in functional components. In this blog post, we’ve explored its basic syntax, demonstrated fetching data with JSONPlaceholder using the Fetch API, and discussed how to use dependencies for more dynamic effects.

Please do not post any spam link in the comment box😊

إرسال تعليق (0)
أحدث أقدم