DEV Community

Cover image for UseEffect() Hook for Beginners
Brandon Damue
Brandon Damue

Posted on

UseEffect() Hook for Beginners

In light of my recent articles on React Hooks, I come again with another one this time focusing on the useEffect() hook. This article is specifically tailored for beginners. I believe it is a good place to start if you want to learn about the useEffect() hook. I promise you it's going to be a pleasant ride so stay with me. Let's get to it!

What is the useEffect() hook?

To be able to fully understand what this hook means or what it does, let us examine what an "effect" means in the context of the useEffect() hook. An effect refers to side effects in functional programming. Side effects are operations like; making a call to an API, network requests, setting up timers and so on. If you want to learn more about side effects, check out this article. So what the useEffect() hook does is that it allows you to perform side effects in your components. They were introduced to eliminate the side effects that come with using class-based components.

How to use the useEffect() hook

When you want to perform a particular operation after each render of a component, you can do this using the useEffect() hook. By using this Hook, we tell React that our component needs to do something after it is rendered by passing a function. React remembers the function we passed in useEffect() hook and calls it after the DOM is updated.

By default, useEffect() runs after the first render and after every update. React updates the DOM by the time it runs the effects. useEffect() accepts two arguments however, the second argument is optional.

useEffect(<function>, <dependency>)
Enter fullscreen mode Exit fullscreen mode

Let's see how useEffect() works using a timer.

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 />);
Enter fullscreen mode Exit fullscreen mode

Every time the Timer component renders, the count variable is updated. useEffect runs on every render. That means that when the count changes, a render happens, which then triggers another effect. There are several ways to control when side effects run. You should always include the second argument which accepts an array. We can optionally pass dependencies to useEffect() in this array. Let's see how this works.

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 />);
Enter fullscreen mode Exit fullscreen mode

In the code snippet above, useEffect() only runs on the initial or first render.

Conclusion

Using this hook makes dealing with side effects easier. Learning how it works will come easy to you if you keep at it. I'll end this article with links to other React Hooks related articles I have written in the past.

I'm looking forward to writing another article on React soon. Until then, Goodbye!

Top comments (5)

Collapse
 
bcostaaa01 profile image
Bruno

Nice read, but I would like to make a point here by applying a best practice.

I would add the following cleanup function:


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

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

  useEffect(() => {
    const interval = setInterval(() => {
      setCount((count) => count + 1);
    }, 1000);
    return () => clearInterval(interval);
  }, []);

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

ReactDOM.render(<Timer />, document.getElementById("root"));
Enter fullscreen mode Exit fullscreen mode
  • the cleanup function here is used to clear the interval, so that it doesn’t keep running even when the component is no longer in the UI.

That way, you have a usage of the useEffect hook applying best practices.

Collapse
 
brandondamue profile image
Brandon Damue

Thank you Bruno for this pertinent contribution. It is very much appreciated

Collapse
 
bcostaaa01 profile image
Bruno • Edited

You are welcome, @brandonbawe!πŸ™‚I look forward to more articles on ReactJS!πŸ™Œ

Thread Thread
 
brandondamue profile image
Brandon Damue

For sure Bruno ☺️☺️

Collapse
 
reacthunter0324 profile image
React Hunter

It's like React Hooks tutorial!