If you pass undefined as the value of the array, it's the same as passing no value at all, i.e. the code will run on every render.

If, OTOH you pass [undefined] as the value of the array, it's the same as passing an empty array ([]) or an array of values that never change. I.e. the code will run only on the initial render.

Answer from Marcus Junius Brutus on Stack Overflow
🌐
React
react.dev › reference › react › useEffect
useEffect – React
If you omit this argument, your Effect will re-run after every commit of the component. See the difference between passing an array of dependencies, an empty array, and no dependencies at all. useEffect returns undefined.
Discussions

What happens with useEffect having either null or undefined as a dependency?
All that React does with dependency arrays is check that the value at each index === the previous value at that index. Both null and undefined will return true if strictly compared against themselves, so having a null or undefined value as a dependency won't trigger the effect as long as it stays null or undefined. Note that null is not strictly equal to undefined or vice versa. So if you have a dependency that changes from null to undefined or vice versa, the effect will fire. More on reddit.com
🌐 r/reactjs
34
21
September 10, 2022
Using a property of initially undefined variable for useEffect dependency
0 ReactJS useEffect not firing on a variable and lint complains about missing dependencies in a different hook More on stackoverflow.com
🌐 stackoverflow.com
January 17, 2020
useEffect should return `undefined`
useEffect should return nothing or undefined. The current implementation of use-effect in react-native ns doesn't always do that. The following example causes it to return the value in the dependency array: (rn/use-effect #(reanimated/se... More on github.com
🌐 github.com
3
January 5, 2023
Why does eslint warn about useEffect having a missing dependency?
I tried to implement a simple data fetching example in ReScript-React, following the article How to fetch data with React Hooks, which I translated into ReScript as: let (items, setItems) = React.useState(() => []) React.useEffect0(() => { fetchData()->Js.Promise.then_(results => { switch results ... More on forum.rescript-lang.org
🌐 forum.rescript-lang.org
0
0
July 8, 2022
🌐
React Native Express
reactnative.express › react › hooks › useeffect
useEffect
If the dependency array is empty or undefined, useEffect will have a different behavior.
🌐
DEV Community
dev.to › amitaldo › function-makes-the-dependencies-of-useeffect-hook-change-on-every-render-warning-in-react-35hd
"Function makes the dependencies of useEffect Hook change on every render" warning in React - DEV Community
March 7, 2023 - Wrapping updateCount in a useCallback hook Let's consider a situation in which you need updateCount to call elsewhere in the component, putting it inside the effect could cause it to be undefined elsewhere. For this solution we need to wrap the updateCount function definition in a useCallback hook. What this does is returns a memoized function whose reference will only change if something in the hook’s dependency array changes. Let’s take a look at the correct implementation: import { useState, useEffect, useCallback } from 'react'; function App() { const [count, setCount] = useState(1); c
🌐
GitHub
github.com › status-im › status-mobile › issues › 14714
useEffect should return `undefined` · Issue #14714 · status-im/status-mobile
January 5, 2023 - useEffect should return nothing or undefined. The current implementation of use-effect in react-native ns doesn't always do that. The following example causes it to return the value in the dependency array: (rn/use-effect #(reanimated/se...
Author   OmarBasem
🌐
React Express
react.express › hooks › useeffect
useEffect
Here, we use useEffect to change ... is listed as a dependency. If the dependency array is empty or undefined, useEffect will have a different behavior....
Find elsewhere
🌐
Hacker News
news.ycombinator.com › item
useEffect is treating undefined as *meaning undefined*. It makes perfect sense f... | Hacker News
December 29, 2022 - It makes perfect sense from inside of useEffect · If there are no dependencies ([]), the dependencies can never change, so React can always reuse the old effect
🌐
ReScript Forum
forum.rescript-lang.org › t › why-does-eslint-warn-about-useeffect-having-a-missing-dependency › 3534
Why does eslint warn about useEffect having a missing dependency? - react - ReScript Forum
July 8, 2022 - I tried to implement a simple data fetching example in ReScript-React, following the article How to fetch data with React Hooks, which I translated into ReScript as: let (items, setItems) = React.useState(() => []) React.useEffect0(() => { fetchData()->Js.Promise.then_(results => { switch results { | Belt.Result.Ok(data) => setItems(_ => data) Js.Promise.resolve() | Belt.Result.Error(msg) => Js.Console.log("Fetching data failed with error: " ++ msg) Js.Prom...
🌐
freeCodeCamp
freecodecamp.org › news › most-common-react-useeffect-problems-and-how-to-fix-them
React.useEffect Hook – Common Problems and How to Fix Them
October 14, 2021 - React Hook useEffect has a missing dependency: 'user'. Either include it or remove the dependency array.
Top answer
1 of 1
65

For this exact case you're right because undefined is passed as the dependencies of useEffect.

This means useEffect runs on every render and thus the event handlers will unnecessarily get detached and reattached on each render.

function listener() {
  console.log('click');
}

function Example() {
  const [count, setCount] = window.React.useState(0);

  window.React.useEffect(() => {

    console.log(`adding listener ${count}`);
    window.addEventListener("click", listener);

    return () => {
      console.log(`removing listener ${count}`);
      window.removeEventListener("click", listener);
    };
  }); // <-- because we're not passing anything here, we have an effect on each render
  
  window.React.useEffect(() => {
    setTimeout(() => {
      setCount(count + 1);
    }, 1000)
  });
  
  return count;
}

window.ReactDOM.render(window.React.createElement(Example), document.getElementById('root'))
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>

But if you explicitly declare no dependencies by passing in an empty array [], useEffect will only run once, thus making this pattern perfectly legitimate for event handler attachment.

function listener() {
  console.log('click');
}

function Example() {
  const [count, setCount] = window.React.useState(0);

  window.React.useEffect(() => {

    console.log(`adding listener ${count}`);
    window.addEventListener("click", listener);

    return () => {
      console.log(`removing listener ${count}`);
      window.removeEventListener("click", listener);
    };
  }, []); // <-- we can control for this effect to run only once during the lifetime of this component
  
  window.React.useEffect(() => {
    setTimeout(() => {
      setCount(count + 1);
    }, 1000)
  });
  
  return count;
}

window.ReactDOM.render(window.React.createElement(Example), document.getElementById('root'))
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>

🌐
Medium
medium.com › @piccosupport › fixing-react-context-undefined-issue-on-first-login-with-useeffect-de5278164413
Fixing React Context Undefined Issue on First Login with useEffect | by Piccosupport | Medium
January 11, 2024 - ... To address this issue, we need to modify the useEffect hook in the context provider to re-run the onLoad function whenever the isAuthenticated state changes. By doing so, we ensure that the user data is fetched and the component is updated ...
🌐
Kinsta®
kinsta.com › home › resource center › blog › react errors › how to fix the “react hook useeffect has a missing dependency” error
How To Fix the “React Hook useEffect Has a Missing Dependency” Error
October 1, 2025 - In this article, we will discuss ... Hook useEffect has a missing dependency” error occurs when the useEffect Hook has a dependency array that is incomplete or missing....
🌐
Reddit
reddit.com › r/reactjs › i call functions in useeffect and get undefined
r/reactjs on Reddit: I call functions in useEffect and get undefined
March 9, 2023 -

So I call two functions in useEffect - getIds() and getNews() which set the results to states newsIds and latestNews. Without newsIds I can't get latestNews so I first need to get ids.

The thing is, with this code I get undefined on each console.log twice. If I remove empy array from the useEffect dependencies, I get what I need because it sends infinite api calls and on third api request and the following I get the results. But of course I don't want to have infinite requests running.

So what's causing it? did I do something wrong in useEffect or in functions?

Thank you so much.

export function NewsCardList() {
const [newsIds, setNewsIds] = useState<number[]>(); 
const [latestNews, setLatestNews] = useState<NewsItem[]>();


const getIds = async () => { 
await fetch(https://hacker-news.firebaseio.com/v0/newstories.json) 
.then((res) => res.json()) 
.then((data: number[]) => data.filter((id: number, i: number) => i < 100))
.then((data) => setNewsIds(data)) 
.catch((e) => console.log(e)); 
};

const getNews = async () => { 
let urls = newsIds && newsIds?.map((id) =>
https://hackernews.firebaseio.com/v0/item/${id}.json); 

let requests = urls && urls.map((url) => fetch(url)); 
console.log(urls); 
console.log(requests); 
requests && await Promise.all(requests)
.then((responses) => Promise.all(responses.map((r) => r.json()))
.then((news) => setLatestNews(news))); 
};

useEffect(() => { 
getIds(); 
getNews(); 
console.log(newsIds); 
console.log(latestNews); 
}, []);

return ( 
<> 
{latestNews && latestNews.map((news) => ( 
<NewsCard key={news.id} 
author={news.by} 
title={news.title} 
date={news.time} 
rating={news.score} /> ))} 
</> ); }

Top answer
1 of 3
24
Keep in mind three things: 1. Closures lock everything down. The function defined within your useEffect creates a closure, which locks up all the variable definitions from the time of its creation. So newsIds and latestNews reference the initial constant values from the time the component is first rendered. By time the effect runs, React has exited this component, and those values are only available within this closure, never to be accessible from the outside again. Which leads to the second thing: 2. Dependency arrays must be populated. The only way to create a new closure with new values is by telling React to do it. That's done by adding the variables to the dependency array. If you include newsIds and latestNews in the effect's dependency array, the closure in the effect will recognize the new values and run, causing the new values to show up in the console. This will also cause the fetch calls to run again, though. We'll talk about this after we talk about the third problem: 3. Asynchronous code runs after everything else. Your getIds and getNews functions are asynchronous. That means that, when they're called, they may as well be launched into space for all that the rest of your current code knows about them. Your code is basically doing this: Create a Promise that enqueues getIds to execute after the current code runs. Create a Promise that enqueues getNews to execute after the current code and getIds runs. Print newsIds to console. Print latestNews to console. Now that the current code is finished running, execute the Promises. So there's no way those variables will show what you want -- the values returned by your async calls. So, how can you make this work? Rely on React to rerender when state setters are called. The last thing your async functions do is call your state setters -- setNewsIds and setLatestNews. When a state setter is called, it tells React to rerender -- run the component function again -- with the updated value in useState's result. This means your code has a chance to print out the newest value during this second render cycle. If you want to only show the results once (twice in development mode), you do the logging in their own effects, with the variables in the dependency array. The result looks like this: export function NewsCardList() { const [newsIds, setNewsIds] = useState(); const [latestNews, setLatestNews] = useState(); useEffect(() => { const getIds = async () => { // do fetching, ending with setNewsIds(data); }; const getNews = async () => { // do fetching, ending with setLatestNews(news); }; getIds(); getNews(); }, []); useEffect(() => { console.log(newsIds); }, [newsIds]); useEffect(() => { console.log(latestNews); }, [latestNews]); // return news and the rest of the component } The ideas here are: The async functions are placed inside the effect, because they're basically throwaway code. They're only executed inside the effect, so placing them inside keeps you from having to track them as dependencies. (State setters don't need to be tracked as dependencies.) This leaves an empty dependency array, giving you the desired effect of running the effect only when the component mounts. (It will run twice in development mode, because of how Strict Mode works. Google or go to the docs below for more details.) Each variable gets its own effect, so that the console.log call is only called initially, and when the specific variable changes. If both variables were in the same effect, you'd see three sets of logs: one when they're both undefined, one when the first call updates the variable, and one when the second variable updates, for a total of six lines in the console. By separating them, each effect runs twice, once at initialization and once at update, for a total of four console lines. If you have code that relies on both simultaneously, then it will make more sense to place them in the same effect. Once each async call completes and calls the state setter, the component is rerun with the updated value, and that triggers the appropriate logging useEffect code to run. There's more nuance to this, but hopefully this gives you a start as to how effects and state interact. As always, refer to the React Beta Docs for more details.
2 of 3
1
Console.log is synchronous, whereas your two functions above are async, so they are logging before those functions have been executed and values set. You should be able to fix it by adding the 2 state variables to the dependency array. I would get rid of the newsIds state completely, doesnt seem like you need it.. You can just return the ids from the getIds call into a variable ids in the getNews function. getNews Let ids = await getids() // check for ids, and if they are there, continue your logic to get the news This way, your useEffect will only call getNews() These two videos made async javascript finally stick for me, kinda long but totally worth it. I hope it helps somebody. https://youtu.be/KpGmW_P5Ygg https://youtu.be/O_BYLu0POO0
🌐
DhiWise
dhiwise.com › post › understanding-the-importance-of-the-useeffect-dependency-array-in-react
UseEffect Dependency Array: Best Practices For React ...
August 13, 2025 - What is the Dependency Array in useEffectEmpty Dependency ArrayHow the Dependency Array Works in the Render CycleWhy You Get Missing Dependency WarningsCommon Dependency Array Mistakes and FixesEmpty Array vs No ArrayThe Role of Cleanup FunctionState Variables and Re RendersAdvanced: Functions and Objects in Dependency ArrayData Fetching Example with Custom HookESLint Rule: React Hooks Exhaustive DepsAvoiding Infinite Loops in EffectsWorking with Async Function in useEffectWhen to Omit DependenciesKeeping Effects on Track with the UseEffect Dependency Array
🌐
Bitstack
blog.bitsrc.io › understanding-dependencies-in-useeffect-7afd4df37c96
Understanding Dependencies in useEffect | Bits and Pieces
March 4, 2025 - There is so much confusion around the dependency array used in useEffect that nobody seems to understand what you can and can’t do with dependencies.
🌐
Epic React
epicreact.dev › why-you-shouldnt-put-refs-in-a-dependency-array
Why you shouldn't put refs in a dependency array | Epic React by Kent C. Dodds
July 9, 2024 - This general rule is why if you pass the value of a module-level variable into a dependency array like this you'll get a similar lint warning: ... React Hook React.useEffect has an unnecessary dependency: 'log'.