Generally speaking, using setState inside useEffect will create an infinite loop that most likely you don't want to cause. There are a couple of exceptions to that rule which I will get into later.

useEffect is called after each render and when setState is used inside of it, it will cause the component to re-render which will call useEffect and so on and so on.

One of the popular cases that using useState inside of useEffect will not cause an infinite loop is when you pass an empty array as a second argument to useEffect like useEffect(() => {....}, []) which means that the effect function should be called once: after the first mount/render only. This is used widely when you're doing data fetching in a component and you want to save the request data in the component's state.

Answer from Hossam Mourad on Stack Overflow
๐ŸŒ
React
react.dev โ€บ reference โ€บ react โ€บ useEffect
useEffect โ€“ React
You canโ€™t exclude shoppingCart from dependencies without breaking the reactivity rules. However, you can express that you donโ€™t want a piece of code to โ€œreactโ€ to changes even though it is called from inside an Effect. Declare an Effect Event with the useEffectEvent Hook, and move the code reading shoppingCart inside of it:
๐ŸŒ
React
legacy.reactjs.org โ€บ docs โ€บ hooks-effect.html
Using the Effect Hook โ€“ React
Why is useEffect called inside a component? Placing useEffect inside the component lets us access the count state variable (or any props) right from the effect. We donโ€™t need a special API to read it โ€” itโ€™s already in the function scope.
Discussions

Can I set state inside a useEffect hook
Lets say I have some state that is dependent on some other state (eg when A changes I want B to change). Is it appropriate to create a hook that observes A and sets B inside the useEffect hook? ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Can't use useEffect inside a useEffect (react ts)
You code doesn't make sense. A hook can only be called top level. from React Docs: Don't call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function. Now, if you want to fetch data only one time, can either use the useEffect in the custom hook, or when you call the function, not in both places. You code is messy without line breaks so I can't really figure pint point the issue in the code More on reddit.com
๐ŸŒ r/reactjs
11
0
May 25, 2022
Understanding useEffect()
useEffect runs after each render, unless you include the dependency array. If the array is empty, it only runs after the first render. If it is not empty, it will run after the first render and only after one of the dependencies updates. useEffect is a normal function though it is only called in specific situations. If you have a normal function call in the functional component, that function runs during render, not after. These types of functions are often used to calculate something meant to be rendered. If the function is only defined but not called in the functional component, then you would ostensibly call it when some event occurs (like a click). Basically, useEffect is used to run some sort of logic after the render, not during. That, or it is used to call some logic specifically after a dependency is updated. useEffect is, by design, also used to contain code with side effects. That is, more or less, code that changes things outside of the component. Things like setting cookies or changing some markup (HTML) imperatively. The reason you put this code there is partly because it runs after things are done rendering and the markup is ready to be changed. Another reason is that you can control when it is called. E.g., if you wanted to change the document title and you put it as a regular function call within the functional component, it would be called during each render/update, which would be less performant than putting it in useEffect with an empty dependency array, which would call it once. Also, if you wanted to update the document title only after the page is ready (maybe because it depends on some data that wouldn't yet be available), you couldn't do that by calling it as a regular function inside the component. More on reddit.com
๐ŸŒ r/react
11
March 20, 2022
how to get an useEffect inside a function in React?
I'm trying to make an countdown website for a project. I want that the countdown is triggered by a button. I'm using React but i keep getting this error React Hook "useEffect" is called in More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
Overreacted
overreacted.io โ€บ a-complete-guide-to-useeffect
A Complete Guide to useEffect โ€” overreacted
This article is a good primer on data fetching with useEffect. Make sure to read it to the end! Itโ€™s not as long as this one. [] means the effect doesnโ€™t use any value that participates in React data flow, and is for that reason safe to apply once. It is also a common source of bugs when the value actually is used.
๐ŸŒ
W3Schools
w3schools.com โ€บ react โ€บ react_useeffect.asp
React useEffect Hooks
The useEffect Hook allows you to perform side effects in your components.
Top answer
1 of 6
245

Generally speaking, using setState inside useEffect will create an infinite loop that most likely you don't want to cause. There are a couple of exceptions to that rule which I will get into later.

useEffect is called after each render and when setState is used inside of it, it will cause the component to re-render which will call useEffect and so on and so on.

One of the popular cases that using useState inside of useEffect will not cause an infinite loop is when you pass an empty array as a second argument to useEffect like useEffect(() => {....}, []) which means that the effect function should be called once: after the first mount/render only. This is used widely when you're doing data fetching in a component and you want to save the request data in the component's state.

2 of 6
189

For future purposes, this may help too:

It's ok to use setState in useEffect . To do so, however, you need to ensure you don't unintentionally create an infinite loop.

An infinite loop is not the only problem that may occur. See below:

Imagine that you have a component Comp that receives props from parent and according to a props change, you want to set Comp's state. For some reason, you need to change for each prop in a different useEffect:

DO NOT DO THIS

useEffect(() => {
  setState({ ...state, a: props.a });
}, [props.a]);

useEffect(() => {
  setState({ ...state, b: props.b });
}, [props.b]);

It may never change the state of a , as you can see in this example: https://codesandbox.io/s/confident-lederberg-dtx7w

The reason this occurs is that both useEffect hooks run during the same react render cycle. When props.a and props.b change at the same time, each useEffect captures the same stale state value from before the update. As a result, when the first effect runs, it calls setState({ ...state, a: props.a }) . Then, the second effect runs immediately after and calls setState({ ...state, b: props.b}) with the same stale state value, thereby overwriting the first update. The result is that a never appears to update. The second setState replaces the first one rather than merging the two updates together.

DO THIS INSTEAD

The solution to this problem is to call setState like this:

useEffect(() => {
  setState(previousState => ({ ...previousState, a: props.a }));
}, [props.a]);

useEffect(() => {
  setState(previousState => ({ ...previousState, b: props.b }));
}, [props.b]);

For more information, check the solution here: https://codesandbox.io/s/mutable-surf-nynlx

With this approach, you will always receive the most updated and correct value of the state.

๐ŸŒ
Reddit
reddit.com โ€บ r/reactjs โ€บ can't use useeffect inside a useeffect (react ts)
r/reactjs on Reddit: Can't use useEffect inside a useEffect (react ts)
May 25, 2022 -

I have a custom hook inside my post context file. I use it for the api call. And I call this function inside my page. I want this function to run first when my page is rendering , since I call another function there too. So i tried to put it in a useEffect but it gives me the error that I cant call useEffect inside a useEffect. Any ideas of how to solve this?

Context provider:

export const PostContextProvider = ({ children }: ChildrenType) => {const [data, setData] = useState<Post[]>([]);const [loading, setLoading] = useState(false);const [error, setError] = useState(false);const UsePosts = (url: string) => {const apiCall = useCallback(() => {setLoading(true);// console.log("post run")axios        .get(url)        .then((response) => {setData(response.data);setLoading(false);        })        .catch((err) => {setError(err);        });    }, [url]);useEffect(() => {apiCall();    }, [apiCall]);  };return (<PostContext.Provider

Page:

const { postData, postLoading, postError, getPost, voteHandler } =useContext(PostContext);

const { subredditsData, getSubreddits } = useContext(SubredditContext);

useEffect(() => {

getSubreddits(https://6040c786f34cf600173c8cb7.mockapi.io/subreddits);

getPost(https://6040c786f34cf600173c8cb7.mockapi.io/subreddits/${subredditId}/posts${urlParam}); }, []);

Error says Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component.

๐ŸŒ
LogRocket
blog.logrocket.com โ€บ home โ€บ how to use the useeffect hook in react: a complete guide
How to use the useEffect hook in React: A complete guide - LogRocket Blog
June 3, 2025 - What does this mean, exactly? All external values referenced inside of the useEffect callback function, such as props, state variables, or context variables, are dependencies of the effect.
Find elsewhere
๐ŸŒ
React
react.dev โ€บ reference โ€บ react โ€บ useEffectEvent
useEffectEvent โ€“ React
Effect Events can only be called from inside Effects or other Effect Events. Do not call them during rendering or pass them to other components or Hooks. The eslint-plugin-react-hooks linter enforces this restriction.
๐ŸŒ
Dave Ceddia
daveceddia.com โ€บ useeffect-hook-examples
How the useEffect Hook Works (with Examples)
October 22, 2020 - With the empty array being passed, useEffect will hang on to the first function you pass it, which in turn will hang on to references to all the (maybe stale) variables that were used inside it.
๐ŸŒ
KnowledgeHut
knowledgehut.com โ€บ home โ€บ blog โ€บ software development โ€บ how to use useeffect in react js: a beginner-friendly guide
React useEffect() Hook: Structure, Usage, Examples & Tips
July 22, 2025 - Reactโ€™s useEffect can replicate all these lifecycle methods depending on how you configure the dependency array: For componentDidMount: use an empty dependency array ([]). For componentDidUpdate: include specific dependencies in the array. For componentWillUnmount: return a cleanup function inside useEffect.
๐ŸŒ
Reddit
reddit.com โ€บ r/react โ€บ understanding useeffect()
r/react on Reddit: Understanding useEffect()
March 20, 2022 -

Hi friends !

I'm quite new to ReactJS and there are some concepts that I can't figure out. One of them is useEffect...

I really dont get the difference between using useEffect and simply calling a function... I looked the documentation but it's not clearing my mind...

Someone can explain me useEffect like i was 5 years old ?

Thanks !!

Top answer
1 of 5
10
useEffect runs after each render, unless you include the dependency array. If the array is empty, it only runs after the first render. If it is not empty, it will run after the first render and only after one of the dependencies updates. useEffect is a normal function though it is only called in specific situations. If you have a normal function call in the functional component, that function runs during render, not after. These types of functions are often used to calculate something meant to be rendered. If the function is only defined but not called in the functional component, then you would ostensibly call it when some event occurs (like a click). Basically, useEffect is used to run some sort of logic after the render, not during. That, or it is used to call some logic specifically after a dependency is updated. useEffect is, by design, also used to contain code with side effects. That is, more or less, code that changes things outside of the component. Things like setting cookies or changing some markup (HTML) imperatively. The reason you put this code there is partly because it runs after things are done rendering and the markup is ready to be changed. Another reason is that you can control when it is called. E.g., if you wanted to change the document title and you put it as a regular function call within the functional component, it would be called during each render/update, which would be less performant than putting it in useEffect with an empty dependency array, which would call it once. Also, if you wanted to update the document title only after the page is ready (maybe because it depends on some data that wouldn't yet be available), you couldn't do that by calling it as a regular function inside the component.
2 of 5
6
UseEffect is a dangerous hole that gets abused a lot. But what it holds is a function that gets called when the passed props in an array change. A lot of people use this for an "on mount" type of function. Since if you pass it an empty array, it will just run the one time (the empty array never changes) Other times, you may link it with something like a userId, and any setter functions used. (Look up react lint rules for it) You should reference any variables used inside of it. Since it will be using the old value from before passing it in otherwise you may be using old values
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ how-to-use-the-usestate-and-useeffect-hooks-in-your-project
React Hooks โ€“ How to Use the useState & useEffect Hooks in Your Project
October 8, 2024 - In the code example above, MyComponent is a functional component which utilizes React hooks, specifically useState and useEffect, to handle state management and execute side effects. The useState hook is used to initialize a state variable called data.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ reactjs-useeffect-hook
React useEffect Hook %%page%% %%sep%% %%sitename%% - GeeksforGeeks
Use multiple useEffect hooks for different concerns: Split logic into separate effects to keep your code organized and readable. Cleanup effects: If your effect involves timers, subscriptions, or external resources, return a cleanup function to prevent memory leaks. Avoid heavy logic inside useEffect: Keep the logic inside useEffect simple.
Published ย  April 12, 2025
๐ŸŒ
Hygraph
hygraph.com โ€บ blog โ€บ react-useeffect-a-complete-guide
React useEffect() - A complete guide | Hygraph
January 21, 2026 - As mentioned, the useEffect Hook allows you to perform common side effects in function components. These side effects are tasks outside the component scope, such as fetching data, interacting with the DOM, or managing subscriptions.
๐ŸŒ
Design+Code
designcode.io โ€บ react-hooks-handbook-useeffect-hook
useEffect Hook - React Hooks Handbook - Design+Code
React is known for its powerful state management process that doesn't require any page reload. One of the tools used for managing the state is the useEffect hook, that deals with the component's lifecycle.
๐ŸŒ
React
react.dev โ€บ learn โ€บ you-might-not-need-an-effect
You Might Not Need an Effect โ€“ React
useEffect(() => { setComment(''); }, [userId]); // ... } This is inefficient because ProfilePage and its children will first render with the stale value, and then render again. It is also complicated because youโ€™d need to do this in every component that has some state inside ProfilePage.
๐ŸŒ
DEV Community
dev.to โ€บ spukas โ€บ 4-ways-to-useeffect-pf6
4 Ways to useEffect() - DEV Community
September 15, 2019 - The main difference is that lifecycle methods always have the reference to the latest state, while useEffect() will cash the state, handlers and effects of each render, and it will be different from the next one. But the good thing is that you can manipulate when to call the function inside useEffect() by specifying a dependency list or none.