DEV Community

Lautaro Suarez
Lautaro Suarez

Posted on

43 6 2 3 3

'useEffect' in depth

What is useEffect for?

useEffect was introduced in react 16.8, before this was released react developers would use componentDidMount and componentWillUnmount.
The useEffect hook is a built-in React hook that allows you to run side effects in functional components. This side effects are actions that do not directly affect the UI but it can include things like fetching data, adding event listeners, etc.

Why useEffect accept two arguments?

It takes two arguments, the first argument being a function that contains the code for the side effect you want to perform and the second argument which is optional being how many times we want it to be perform.

First Example

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

function Timer() {
  const [time, setTime] = useState(0);

  useEffect(() => {
    const intervalId = setInterval(() => {
      setTime(prevTime => prevTime + 1);
    }, 1000);
  }, []);

  return <div>{time} seconds have passed.</div>;
}
Enter fullscreen mode Exit fullscreen mode

In the example above it will run just once after the component in mounted.

Second Example

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

function Timer() {
  const [time, setTime] = useState(0);

  useEffect(() => {
    const intervalId = setInterval(() => {
      setTime(prevTime => prevTime + 1);
    }, 1000);
  }, [time]); 

  return <div>{time} seconds have passed.</div>;
}
Enter fullscreen mode Exit fullscreen mode

In the example above we can see how i passed the second argument so it just renders every time 'time' changes.

Cleanup in useEffect?

This is something not always is being used or even taught, but is indeed really important for time efficient and memory leaks.
We should run cleanup in useEffect to we avoid having memory leaks in our application which can cause our app to be slower.

Example with cleanup

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

function Timer() {
  const [time, setTime] = useState(0);

  useEffect(() => {
    const intervalId = setInterval(() => {
      setTime(prevTime => prevTime + 1);
    }, 1000);

    return () => {
      clearInterval(intervalId);
    };
  }, [time]);

  return <div>{time} seconds have passed.</div>;
}
Enter fullscreen mode Exit fullscreen mode

In the example above we can see that i added a return which will return a clearInterval that will do a cleanup with the intervalId and we will avoid memory leaks in our application.

Hope someone found this useFul and if you have any questions and would be happy to answer them.

Lautaro.

Billboard image

Imagine monitoring that's actually built for developers

Join Vercel, CrowdStrike, and thousands of other teams that trust Checkly to streamline monitor creation and configuration with Monitoring as Code.

Start Monitoring

Top comments (5)

Collapse
 
florianrappl profile image
Florian Rappl

For an article titled "in depth" its rather shallow and is also not fully accurate.

  1. The second argument is optional - if no dependency array is passed in then it just runs on every render.
  2. The dependency array is actually crucial. You should add information that it makes a shallow comparison. So, as an example, instead of passing in an object or so you should try to make to only pass in the used properties of an object.
  3. There is also useLayoutEffect - while this article is about useEffect it would still be really good to highlight why there are two different hooks and what is the difference.

Personally, I loved the useFul joke. Not sure if it was intentional though or just a typo.

Collapse
 
lausuarez02 profile image
Lautaro Suarez

I appreciate your answer Florian.
I missed some really importante points that i took from granted, on next posts i will explain more in depth as the title says what would happen depending on the situation.

And yeah, i always put the same joke on every post and you are the first one who understand it was a joke.

Again, thank you for the comment.

Collapse
 
creasser profile image
Blake Creasser

Love it, short and concise but good information!

Collapse
 
lausuarez02 profile image
Lautaro Suarez

Thank you man, i usually try to do short posts but with good info

Collapse
 
reacthunter0324 profile image
React Hunter

It described 3 functionalities.
Looks Good!

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay