Home » useEffect Hooks

useEffect Hooks

useEffect Hooks

Introduction

In this, we are going to focus on a React hook called useEffect. A hook that is pretty complex at first, but after today you will get a good grasp on how everything works.

The outcome from a Component is to render “something” on the user interface with the rendering logic(written in JSX). Many factors drive the rendering logic,

  • The state values are defined and updated inside a component.
  • The props values are passed to the component.
  • The side effects.

Now, what are the side effects? It is okay if you haven’t heard it before in the context of programming. Let us break it and understand here.

  • A side-effect can be any effect(programming logic) that is responsible for changing the state of your component. If the state changes, the component re-renders. For example, a typical side effect is making an API call and changing the local state of a component to store the API response data and then component will re-render.

Why we need the useEffect Hook?

So, a side effect is something that we should isolate from the rendering. The useEffect hook helps perform side effects by isolating it from the rendering logic. So, in the world of React components, useEffect is like a set of instructions for your component, telling it when to do certain things. It helps you control when to run different parts of your code, making sure everything happens at the right time,

useEffect(callback, [dependencies]);
JavaScript

The useEffect hook takes two arguments,

  • A callback function to define and clean up a side effect.
  • An optional dependency array that ensures when to run a side effect defined inside the callback function.

The Advantages of Using useEffect in React

In React, useEffect is particularly useful because it provides a clean and centralized way to manage side effects in functional components. While it’s true that you can perform certain side effects without using useEffect, using this hook has several advantages:

  1. Separation of Concerns: useEffect helps in separating the logic related to side effects from the rest of the component’s code. This makes your component more modular and easier to understand. Without useEffect, side effect code might be scattered throughout the component, leading to a less organized and maintainable codebase.
  2. Timing and Lifecycle Management: useEffect allows you to specify exactly when your side effect code should run, whether it’s after the initial render, after every render, or based on changes in specific dependencies. This level of control helps in managing the timing of operations more effectively.
  3. Avoiding Infinite Loops: In a component’s lifecycle, certain actions may cause a re-render. Without useEffect, if the code inside a component triggers a state update, it could lead to an infinite loop of re-renders. useEffect allows you to control when the side effect code runs, preventing unintended loops.
  4. Cleanup: useEffect provides a mechanism for cleanup operations. If your side effect involves setting up subscriptions, timers, or any resource that needs to be released, you can return a cleanup function from the effect. This ensures that resources are properly released when the component is unmounted or updated.
  5. Consistent API for Side Effects: By using useEffect, you adopt a consistent and predictable API for handling side effects across different components. This standardization makes your codebase more maintainable and helps other developers understand how side effects are managed in your application.

The useEffect Hook Usages:-

The callback function we pass to the useEffect hook runs the side effects. React runs it on every render of a component by default. However, side effects can be expensive and performance-intensive to run on every render. We can control it using the dependency array argument we pass to the useEffect hook.

Let’s understand the useEffect hooks:-

useEffect has three Step and we will see it by making a project:-

  • component Mount
  • Did Component Update
  • component Unmount

useEffect on Component Mount:

Here is a simple Website using React js:

In the developer console , you will notice ‘mount‘ has been logged. And every time you refresh you will see ‘mount‘ reappear in the console.

So far, this tell us that every time the component App is mounted onto the DOM the useEffect is called.

UseEffect on State Update:-

Here is a simple Website using React js:-

As you interact with both buttons, you will notice that the developer console doesn’t relog “mount.” It only logged “mount” after the component has been mounted.

useEffect with an empty dependency array will only be called once after the component has mounted.

UseEffect With A Dependency When State Are Updated or Did Component Update:

The useEffect hook calls the function after the component mounts and then calls it again every time count updates. By passing only count as a dependency to the useEffect hook, we tell useEffect to call the function again only when the count state variable changes.

So till now you know about component Mount , and Did component Update.

Let’s see what is Component Unmount ?

“Component unmount” refers to the process of removing a component from the user interface. When a component unmounts, it is no longer displayed or active in the application. This can happen when you navigate away from a page or close a part of the user interface. During the unmounting process, any cleanup or actions specified for the component can be performed, ensuring that resources are released and the component no longer affects the application.

Here’s what’s happening step by step:

  1. Initially, the count is set to 0.
  2. When you click the “increase” button, the increase function is called. It increments the count variable and updates the state using SetCount(count).
  3. The state change triggers the useEffect because it’s listening to changes in the count variable.
  4. The “I am changed” message is logged to the console.
  5. When you click the button again, the same process occurs, and the previous useEffect cleanup function is called, logging “unmount” with the previous value of count - 1.

The useEffect Hook allows you to perform side effects in your components.

useEffect accepts two arguments. The second one is optional.

Runs on every render:

import { useState, useEffect } from "react";

function Home() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    setTimeout(() => {
      setCount((count) => count + 1);
    }, 1000);
  });

  return <h1>I have rendered {count} times!</h1>;
}

export default Home;
JavaScript

Runs on first render:

import { useState, useEffect } from "react";

function Home() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    setTimeout(() => {
      setCount((count) => count + 1);
    }, 1000);
  }, []);

  return <h1>I have rendered {count} times!</h1>;
}

export default Home;
JavaScript

Runs when data changes:

import { useState, useEffect } from "react";

function Home() {
  const [count, setCount] = useState(0);
  const [data, setData] = useState('');

  const handleChange = (e) => {
    setData(e.target.value)
  }

  useEffect(() => {
    setCount((count) => count + 1);
  }, [data]);

  return (
    <>
      <input onChange={handleChange} value={data} />
      <p>{count}</p>
    </>
  );
}

export default Home;
JavaScript

Conclusion

The useEffect hook is a powerful tool in React for managing side effects in function components. Whether you need to fetch data, subscribe to events, or perform cleanup, useEffect provides a clean and concise way to handle these scenarios. By understanding its behavior and utilizing dependency arrays effectively, you can write more efficient and maintainable React code.

Frequently Asked Question

1.What is the useEffect hook in React?

useEffect is a hook in React that allows you to perform side effects in function components. It’s similar to lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount in class components.

2. When does the useEffect hook run?

useEffect runs after every render of the component by default. You can control when it runs by passing a second argument (dependency array), specifying which values should trigger the effect.

3. How do I perform cleanup with useEffect?

You can return a cleanup function from the useEffect callback. This function will run before the component is removed from the UI or re-rendered. It’s useful for tasks like unsubscribing from subscriptions or clearing timers.