Author -  Sai gowtham

Intro to the React useEffect hook

In this tutorial, we are going to learn about how to use the useEffect hook in react with the help of examples.

Note: If you don’t know about hooks then check out my react hooks introduction.

useEffect hook

The useEffect hook helps us to use the lifecycle methods in functional components.

They are three lifecycle methods we can use in useEffect hook which are componentDidMount, componentDidUpdate, and componentWillUnmount.

Let’s learn the useEffect by using examples.

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

function App() {
  const [value, setValue] = useState(0);

 // this function runs when component mounts and component updates  useEffect(() => {    document.title = "My app";  });
  return (
    <div className="App">
      <h1>{value}</h1>
      <button onClick={() => setValue(value+1)}>Increment</button>
    </div>
  );
}

In the above code, we imported two hooks which are useEffect and useState.

If you don’t know about useState hook then checkout my previous tutorial

The useEffect hook takes the function as an argument and run the function whenever the component mounts to the DOM.

We also added an increment button which is used to increment the value and re-renders the dom but whenever the component is re-rendered useEffect re-runs the function we passed as an argument because currently, we activated two lifecycle methods componentDidMount, componentDidUpdate.

To stop the componentDidUpdate lifecycle method we need to pass an empty array[] as a second argument to the useEffect hook.

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

function App() {
  const [value, setValue] = useState(0);

//The function only runs when component mounts to dom  useEffect(() => {    document.title = "My app";  },[]);
  return (
    <div className="App">
      <h1>{value}</h1>
      <button onClick={() => setValue(value+1)}>Increment</button>
    </div>
  );
}

Now, we stopped running the function when a component is re-rendered.

Instead of leaving the array empty, we can also pass a conditional value to the array to run the function whenever the given condition is true.

function App() {
  const [value, setValue] = useState(0);
  const [active, setActive] = useState(false);

//The function runs when component mounts to dom
  useEffect(
    () => {
      document.title = "My app";
      if (value === 5) {
        setActive(!active);      }
    },
    // re-run the function when  value === 5
    [value === 5]  );

  return (
    <div className="App">
      <h1>{value}</h1>
      {/*We only disabled the button when value===5*/}
      <button onClick={() => setValue(value + 1)} disabled={active}>
        Increment
      </button>
      {active && <p>You've reached your limit for today</p>}
    </div>
  );
}

In the above code, we passed the conditional value===5 to the array so that the function runs initially when component mounts to dom and it runs again when the value reaches to 5.

useeffect hook conditional check

Have you seen in the above image we disabled the button when the value reaches to 5?

useEffect hook Data Fetching example

We can also use the useEffect hook for the data fetching in functional components.

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

const useFetch = url => {
  const [data, setData] = useState(null);

  async function fetchData() {
    const response = await fetch(url);    const json = await response.json();
    setData(json);  }

  useEffect(() => {fetchData()},[url]);
  return data;
};

function App() {

  const data = useFetch("https://jsonplaceholder.typicode.com/todos/1");

  if (!data) {
    return <div>Loading...</div>;
  } else {
    return (
      <ul>
        <li>{data.id}</li>
        <li>{data.title}</li>
      </ul>
    )
  }
}

export default App;

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2023 (Beginner + Advanced)
JavaScript - The Complete Guide 2023 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY