Using the Effect Hook

Rubleen Kaur
Last Updated: May 13, 2022

Introduction

Hooks in React allows you to hook into the react state and lifestyle features through the function component. Hooks are a new feature update of the React in version 16.81. Hooks allow us to use the functionality of various states and React features without using the class. The useEffect() considers a function observing input and returns nothing; it runs additional code after render. We can see it as a combination of React Component lifecycle methods: componentDidMountcomponentDidUpdate, and componentWillUnmount. Using Effect Hooks, we can add listeners after the component has been rendered. The Effect Hook allows us to perform side effects in function components. Functions like data fetching, setting up a subscription, and manually changing the DOM in React components are part of these side effects. They can also be just called effects.

There are two different types of side effects which the React Hook provides us:

  • Effects without a CleanUp
  • Effects with a CleanUp

Effects without Cleanup

Effect Hooks without cleanup are used in useEffect, so it does not block the browser from updating the screen. This makes our app more responsive. The most common effects that don't require a cleanup are manual DOM mutations, Network requests, Logging, etc.

All the examples we have discussed till now are effects that do not require cleanup. 

For example,

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

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

useEffect(() => {
  document.title = `You clicked ${count} times`;
});

 return (
  <div>
    <p>Ninja clicked {count} times</p>
    <button onClick={() => setCount(count + 1)}>Click me</button>
  </div>
);
}

 

OUTPUT

 

 

Effects with Clean Up

In Effect Hooks, we have some effects which require clean-up after the DOM update. For example, if we want to set up a subscription for some external data source, it is essential to clean up memory to avoid a memory leak. React performs the cleanup of memory when the component unmounts. The effects run for every render method and not just once. Therefore, React also cleans up effects from the previous render before running the effects next time. Effect Hooks allows us to use these components effectively. Let’s have a look at an example to understand better. 

For example, 

import React, { useEffect, useState } from "react";
import ReactDOM from "react-dom";

import "./styles.css";

import fetch from "./fake-fetch";

function Employees() {
 const [list, setList] = useState(null);

useEffect(() => {
  let controller = new AbortController();
  (async () => {
    try {
      const response = await fetch("/employees/list", {
        signal: controller.signal
      });
      setList(await response.json());
      controller = null;
    } catch (e) {
      // Handle fetch error.
    }
  })();
  return () => controller?.abort();
}, []);

 return (
  <div className="list">
    {list === null ? "Fetching employees..." : null}
    {list?.map((name) => (
      <div className="item" key={name}>
        {name}
      </div>
    ))}
  </div>
);
}

function About() {
 return (
  <div className="about">
    <p>Coding Ninjas provides the best curated content.</p>
    <p>Happy Learning Ninjas!</p>
  </div>
);
}

function App() {
 const [page, setPage] = useState("employees");

 const showEmployeesPage = () => setPage("employees");
 const showAboutPage = () => setPage("about");

 return (
  <div className="App">
    <h2>Ninja List</h2>
    <a href="#" onClick={showEmployeesPage}>
      Ninjas List
    </a>
    &nbsp;
    <a href="#" onClick={showAboutPage}>
      About Us
    </a>
    {page === "employees" ? <Employees /> : <About />}
  </div>
);
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

 

OUTPUT

 

 

The effect hook unifies both the use cases by using a single API reference.

 

Frequently Asked Questions

  1. What are React Hooks?

    Ans: Hooks in React allows you to hook into the react state and lifestyle features through the function component. Hooks are a new feature update of the React in version 16.81. Hooks allow us to use the functionality of various states and React features without using the class. Hooks allow you to create an entire React Application with just functional components.

     
  2. What is the use of useEffect?

    Ans: With the use of this Hook, we can tell React that our component needs to do something after render. React will store the function you passed in the memory and this function is known as the effect, it is later called after the DOM updates have been performed. 

     
  3. Why is the useEffect method called inside the component?

    Ans:  By placing our useEffect method inside the component, we can access the count state variable right from the effect itself. We do not need any particular API to read the variable, and we have it directly in the function scope.

     
  4. What is an Effect Hook?

    Ans: The Effect Hook allows us to perform side effects in function components. Functions like data fetching, setting up a subscription, and manually changing the DOM in React components are part of these side effects. They can also be just called effects.

Key Takeaways

Hey everyone, so let’s brief out the article. Let’s discuss in brief whatever we have discussed here. 

  • The Effect Hook allows us to perform side effects in function components. Functions like data fetching, setting up a subscription, and manually changing the DOM in React components are part of these side effects. They can also be just called effects.
  • After discussing the basics of Effect hooks, we have gone over the two available types of side effects, the effects without a cleanup and the effects with a cleanup.
  • The article then covers the most frequently asked questions from the developers about the use of Effect Hooks. 

 

Isn’t Web Development engaging? Building new websites and using amazing animations and different APIs, don’t be scared if you cannot grasp the hold of this vast development. We have the perfect web development course for you to make you stand out from your fellow developers. 

Happy Learning Ninjas!

 

 

Was this article helpful ?
0 upvotes