Simplified Guide to useEffect in React

Published on
Jigar Patel-
5 min read

Overview

ExpertLaravel.com Image

Simplified Guide to useEffect in React

Effects play a vital role in managing data flow in your app.

useeffect

Introduction

If you've used React Hooks, you might have encountered situations where things didn't quite fit. Questions about replicating behaviors with useEffect or issues like infinite loops may arise. This guide aims to demystify these aspects and provide a clear understanding of useEffect.

Basic Syntax

The basic syntax of the useEffect hook is as follows:

import { useEffect } from 'react';

function ExampleComponent() {
  useEffect(
    () => {
      // Side effect code here
      // This code will run after every render
      return () => {
        // Cleanup code here
        // This function will run before the component unmounts
      };
    },
    [
      /* dependencies */
    ]
  );

  // Component JSX and logic
}

Code Example: Fetching Data Using useEffect

In this example, we'll explore how to use the useEffect hook to fetch data from an API when a component mounts. This is a common use case that demonstrates the power of useEffect in managing side effects.

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

function DataFetchingComponent() {
  const [data, setData] = useState([]);

  useEffect(() => {
    // Fetch data from API
    fetch('https://api.example.com/data')
      .then((response) => response.json())
      .then((data) => {
        setData(data); // Update component state with fetched data
      });

    // Cleanup function (optional)
    return () => {
      // Cancel any ongoing requests or perform cleanup tasks
    };
  }, []); // Empty dependency array means the effect runs only on mount

  return (
    <div>
      <h2>Fetched Data</h2>
      <ul>
        {data.map((item) => (
          <li key={item.id}>{item.name}</li>
        ))}
      </ul>
    </div>
  );
}

export default DataFetchingComponent;

In this example, the useEffect hook is used to fetch data from the API. The effect runs only once, when the component mounts, because the dependency array [ ] is empty. This means that the effect will not re-run if component state or props change. The fetched data is then stored in the component's state using the useState hook.

Subscribing to WebSocket Events:

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

function WebSocketExample() {
  const [message, setMessage] = useState('');

  useEffect(() => {
    const socket = new WebSocket('wss://api.example.com/socket');

    socket.addEventListener('message', (event) => {
      setMessage(event.data);
    });

    return () => {
      socket.close();
    };
  }, []);

  return (
    <div>
      <h1>WebSocket Example</h1>
      <p>Received: {message}</p>
    </div>
  );
}

export default WebSocketExample;

This example demonstrates how to use the useEffect hook to manage the WebSocket subscription and cleanup within a React Component. The component establishes a WebSocket connection when it mounts, listens for incoming messages, updates the UI with received data, and ensures the connection is closed when the component is unmounted.

Handling Document Title Changes:

import React, { useEffect } from 'react';

function DocumentTitleExample() {
  useEffect(() => {
    document.title = 'New Page Title';
    return () => {
      document.title = 'Default Title';
    };
  }, []);

  return (
    <div>
      <h1>Document Title Example</h1>
      <p>This component will change the document title.</p>
    </div>
  );
}

export default DocumentTitleExample;

The DocumentTitleExample component uses the useEffect hook to dynamically modify the browser tab's title when the component is mounted and ensures that the title is reset when the component is unmounted or re-rendered. This behavior is especially useful when you want to provide meaningful titles for different sections of your application or website.

Remember that the second argument of useEffect (an array of dependencies) is crucial. If you pass an empty array ([]), the effect will only run once after the initial render. If you pass a variable in the array, the effect will run whenever that variable changes. Omitting the array will cause the effect to run after every render.

Please note that while these examples provide a solid foundation, you might need to modify them to suit your specific use case. Always consider error handling and edge cases when implementing useEffect in your application.

Quick summary

The useEffect hook is a powerful tool for managing side effects in React functional components. Whether you're fetching data, interacting with APIs, or handling subscriptions, useEffect provides a clean and declarative way to incorporate side effects into your components. By carefully managing the dependency array, you can control when the effect runs and ensure optimal performance. Embrace the flexibility of useEffect to create dynamic and engaging React applications.

About the Author

Jigar Patel is a React.js enthusiast and a software developer at JBCodeapp Company. Visit our JBCodeapp to learn more about our work in the React.js ecosystem.

We're Hiring

Are you passionate about React.js development? We're always on the lookout for talented developers to join our team. Check out our careers page for current job openings.

  • React.js Short Code Examples: A Quick Guide for Beginners

  • Redirecting to Another Page in 5 Seconds with jQuery in React

  • Creating a Secure Login Page in React: User Authentication Example

  • Mastering React: Your Go-To Guide for 2023

  • Learn React.js Step by Step

  • Key JavaScript Concepts Every React Developer Should Know

  • How to Allow Only Numbers in React Textboxes

  • How to Start a React Project in 2023

  • Getting Started with Create React App