DEV Community 👩‍💻👨‍💻

Cover image for Why we use empty array with UseEffect
Clara Situma
Clara Situma

Posted on

Why we use empty array with UseEffect

If you do not pass an empty array as an argument to useEffect,
the effect will run on every render of the component.

This means that any code inside the useEffect callback will be executed on initial render, and on subsequent updates to the component.

Here is an example of using useEffect without an empty array:


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

function MyComponent() {
  const [data, setData] = useState(null);

  useEffect(() => {
    // This will run on every render of the component
    fetchData().then(response => setData(response));
  });

  return (
    // component render code here
  );
}

Enter fullscreen mode Exit fullscreen mode

In this example, useEffect is used to fetch data from an API on every render of the component. This means that the fetchData function will be called o*n initial render, and **on every subsequent update to the component.*

This can lead to unnecessary network requests and can negatively impact the performance of your application.

If you do not want the useEffect callback to run on every render, you should pass an empty array as an argument to useEffect.

This tells React that the effect does not depend on any values from the component's props or state, so it only needs to be run once on initial render.

Here is an example of using useEffect with an empty array:


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

function MyComponent() {
  const [data, setData] = useState(null);

  useEffect(() => {
    // This will only run on initial render
    fetchData().then(response => setData(response));
  }, []);

  return (
    // component render code here
  );
}
Enter fullscreen mode Exit fullscreen mode

In this example, useEffect is used to fetch data from an API when the component is first rendered.

The empty array as an argument to useEffect means that the fetchData function will only be called on initial render, and not on subsequent renders when the data state changes.

This helps to avoid unnecessary network requests and can improve performance.

Top comments (1)

Collapse
 
brense profile image
Rense Bakker •

Bonus points if you also add a cleanup to your useEffect, to cancel the request when the component gets unmounted during fetching. In your current code the state update will produce an error if the component gets unmounted during fetching (cant update state of unmounted component).

🤯

"I made 10x faster JSON.stringify() functions, even type safe"

☝️ Must read for JS devs