E2EHIRING Logo
Jobs
Jobs
courses
Courses
mentorship
Mentorship
more
Moredropdown
E2EHIRING Logo
more
Jobs
Jobs
courses
Courses
mentorship
Mentorship
HomeSepratorIconBlogsSepratorIconReact (How to use useEffect Hooks)SepratorIcon

React (How to use useEffect Hooks)

Han SoloAnbarasan Murugan
calendar27 Jun 2022
poster

React  useEffect Hooks:

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

Some examples of side effects are: fetching data, directly updating the DOM, and timers.

useEffect accepts two arguments. The second argument is optional.

useEffect(<function>,<dependancy>)

Example:

Use  setTimeout() to count 1 second after initial render:

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

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

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

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

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Timer />);
Output:
I've  rendered 0 times! (Its increase 1 by 1)

But wait!! It keeps counting even though it should only count once!

useEffect runs on every render. That means that when the count changes, a render happens, which then triggers another effect.

This is not what we want. There are several ways to control when side effects run.

We should always include the second parameter which accepts an array. We can optionally pass dependencies to useEffect in this array.

Recent Posts

 Introduction to Java Programming: Basics and Fundamentals

Introduction to Java Programming: Basics and Fundamentals

Introduction to Web Technologies: HTML, CSS, and JavaScript

Introduction to Web Technologies: HTML, CSS, and JavaScript

Introduction of JavaScript

Introduction of JavaScript

Java/Kotlin : Interoperability & Benefits

Java/Kotlin : Interoperability & Benefits

Introduction of Bootstrap

Introduction of Bootstrap

copycopycopycopy

Han Solo

Recent Posts

 Introduction to Java Programming: Basics and Fundamentals

Introduction to Java Programming: Basics and Fundamentals

Introduction to Web Technologies: HTML, CSS, and JavaScript

Introduction to Web Technologies: HTML, CSS, and JavaScript

Introduction of JavaScript

Introduction of JavaScript

Java/Kotlin : Interoperability & Benefits

Java/Kotlin : Interoperability & Benefits

Introduction of Bootstrap

Introduction of Bootstrap