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
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.

Discussions

reactjs - how can I set useState variable under useEffect? - Stack Overflow
I have 1 functions checkCondition that should return true/false based on some logic check. and I will like to pass the return value into the variable isMatched under component. I have tried to use More on stackoverflow.com
🌐 stackoverflow.com
Working of `useState` function inside `useEffect` function
I am trying to use useState inside useEffect. More on stackoverflow.com
🌐 stackoverflow.com
August 16, 2019
useState in useEffect
Tanstack-query is it's own state manager, you shouldn't need to store that data in a separate area of state. You could pass the relevant data directly to the input from the fetched data. When you submit the form you should be able to get the new data from the onSubmit callback. We use react-hook-form in our project to manage form state though which is an entirely different approach. More on reddit.com
🌐 r/reactjs
39
39
December 2, 2023
If I shouldn't fetch in useEffect, where should I fetch?
useEffect should be used to synchronise data from an external source When people say don’t use useEffect is when you are reacting to something within your component, usually if something within the component has changed it’s doing a render so you can simplify your code and put your useEffect code in the event handler or just in your component to run on render. More on reddit.com
🌐 r/reactjs
109
157
September 14, 2024
🌐
React
react.dev › reference › react › useEffect
useEffect – React
Instead, declare it inside the Effect: ... import { useState, useEffect } from 'react'; import { createConnection } from './chat.js'; const serverUrl = 'https://localhost:1234'; function ChatRoom({ roomId }) { const [message, setMessage] = ...
🌐
React
legacy.reactjs.org › docs › hooks-effect.html
Using the Effect Hook – React
function Example() { const [count, setCount] = useState(0); useEffect(() => { document.title = `You clicked ${count} times`; }); } We declare the count state variable, and then we tell React we need to use an effect. We pass a function to the useEffect Hook. This function we pass is our effect. Inside our effect, we set the document title using the document.title browser API.
🌐
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 - This is deemed appropriate because ... by the overarching logic within the component. The React useState Hook enables you to have state variables in functional components....
🌐
Medium
medium.com › @loons.create › react-hooks-how-to-use-usestate-and-useeffect-example-914c161df34d
React Hooks — How To Use useState and useEffect Example | by Asbar Ali | Medium
January 31, 2022 - Mutate the state inside the function and setCount variable use to increment the count state to 1 (Use to mutate the state). This is what we call state hook. Next one is the effect hook. setEffect is used to replace the lifecycle hooks such as componentDidMount, componentDidUpdate and componentWillUnmount. For an example, if your goal is to trigger data fetching upon clicking on a button, then there’s no need to use useEffect.
🌐
DEV Community
dev.to › catur › best-implement-setstate-on-useeffect-3je9
Best Implement setState on useEffect - DEV Community
October 21, 2022 - "Warning: Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render."
Find elsewhere
🌐
Codedamn
codedamn.com › news › react js
Mastering the Use of useState and useEffect Hooks in React.js
May 7, 2023 - A: useState is a hook used to manage state in functional components, while useEffect is a hook used to manage side effects (like fetching data, setting up event listeners, or updating the DOM) in functional components.
🌐
SheCodes
shecodes.io › athena › 125174-difference-between-usestate-and-useeffect-in-react
[React] - Difference between useState and useEffect in | SheCodes
Learn about the difference between useState and useEffect hooks in React, and how they are used for state management and side effects.
🌐
Syncfusion
syncfusion.com › blogs › react › understanding react’s useeffect and usestate hooks
Understanding React’s useEffect and useState Hooks | Syncfusion Blogs
November 6, 2025 - In this article, we discussed how to use two of React’s most essential Hooks: useState and useEffect. If we know the correct usage, they can be used to write cleaner, reusable code.
🌐
Initial Commit
initialcommit.com › blog › usestate-useeffect-hooks-react
A Guide to Using the useState and useEffect Hooks in React
February 23, 2022 - The following code adds to our previous example by using useEffect to change the document title when a new word is added to the list. function App() { const [input, setInput] = useState(""); const [words, setWords] = useState([]); useEffect(() ...
🌐
Ais
ais.com › home › blog › hooked on react: usestate and useeffect
Hooked on React: useState and useEffect - Applied Information Sciences
August 28, 2023 - This useEffect will run only once when the button is clicked. The variable will change from the useState, and will cause the useEffect to run. A couple of things to note about the useEffect are that; the first time it will run is when the component that’s using it is mounted.
🌐
Medium
medium.com › @manojitdas180306 › understanding-the-differences-between-usestate-and-useeffect-in-react-5296ce78d574
Understanding the Differences Between useState and useEffect in React | by Manojit Das | Medium
July 9, 2024 - useState: Manages local state within a component. The state can change and directly affect what is rendered. useEffect: Manages side effects—operations that occur outside of rendering, such as data fetching or subscribing to external events.
🌐
Medium
medium.com › @billybaneydev › passing-down-useeffect-data-in-react-with-usestate-4021187ba849
Passing down useEffect data in React with useState | by Billy Baney | Medium
September 8, 2021 - Through my first two Phases with Flatiron School, I think one of the most useful concepts I picked up was storing data that was fetched from a useEffect, inside of state, so that it could be passed down as props to whatever component may need access to that information. The first step would be to import useState and useEffect at the top of your App.js file, the same place where you import React originally.
🌐
egghead.io
egghead.io › blog › use-react-s-usestate-and-useeffect-hooks
Use React's useState and useEffect Hooks | egghead.io
August 4, 2021 - This is a simple react application with no functionalities at all, and we are going to be adding the counter functionalities by using the useState hook. To get started with implementing these functionalities, the first thing we'll need to do is import the hook we will use. Now, inside your App.js, at the top, import useState from React.
🌐
Linguine Code
linguinecode.com › home › blog › can you setstate in useeffect?
Can you setState in useEffect?
December 22, 2022 - The answer is yes, you can set state inside useEffect, but you shouldn’t as it can cause additional renders or an infinite loop error. Let’s look at some bad examples of using useState inside useEffect.
Top answer
1 of 4
2

I am walking through the code you have put here:

const [isMatched, setMatched] = useState(false)

You have set initial value of isMatched as false.

useEffect(()=>{
  ...
}, [isMatched])

Here the useEffect is registered as callback but not run yet.

console.log({isMatched})

Console logs false because useEffect has not run yet. Then the return() JSX is rendered. Now useEffect is called.

const aa = checkCondition() //aa gets checkCondition value
console.log({aa}) //aa is logged to console
setMatched(aa)//isMatched is set to aa's value, but this update will not happen immediately
console.log({isMatched})//This will output false(since initial value of isMatched is false), setState doesn't update immediately remember?

Each line explained above.

Now this useEffect has been given deps [isMatched], which means this code will run once in the beginning, then every time isMatched value changes. Now why would you want to do this, I don't know, I assume you saw the lint warning saying React Hook React.useEffect has a missing dependency: 'isMatched'. Either include it or remove the dependency array. (react-hooks/exhaustive-deps)eslint and put it there, which is wrong because you are only using it for a console.log. Either way, now whenever you call setMatched with a different value than it was previously(in this cycle previous value is false), it will rerun the useEffect callback.

This means if checkCondition output is true, useEffect will run once more, if it is false it will not. It will not fall into an infinite loop here as boolean values are primitive, so false===false and true===true comparisons are both true. If checkCondition output were a object reference it has the potential to fall into an infinite loop, because the isMatched dependency most likely would point to a different reference every time.

2 of 4
0

To avoid infinite loop as commented, update your state this way,

useEffect(()=>{
  const aa = checkCondition()
  setMatched(() => aa));
}, [])
🌐
Pluralsight
pluralsight.com › tech insights & how-to guides › tech guides & tutorials
Fetching Data and Updating State with Hooks | Pluralsight
May 7, 2025 - The useEffect hook allows you to handle side effects such as logging, making asynchronous calls, or setting values on local storage. The useState hook lets you give state to your functional components, which wasn't possible before unless you ...
Top answer
1 of 3
7

setIsAuth doesn't cause the local variableisAuth to change its value. const data values can't be changed, and even if you defined it as let, that's not what setting state does. Instead, when you set state, the component rerenders. On that new render, the call to useState will return the new value, and you can use that new value for the new render.

The component renders for the first time. Then it runs the effect. The closure for the effect has the local variables from that first render, and your code uses those variables to log the false twice. Since you called set state, a new render will happen, and that new render will have different variables. When it's effect runs, it will log true twice, since that's the values in its closure.

2 of 3
3

Here are some comments in the code explaining how React setState will only update the local const once the component re-renders

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

const Authentication = () => {
    // React will initialise `isAuth` as false
    const [isAuth, setIsAuth] = useState(false);

    useEffect(() => {
        // Console log outputs the initial value, `false`
        console.log(isAuth);
        // React sets state to true, but the new state is not available until
        // `useState` is called on the next render
        setIsAuth(true);

        // `isAuth` will remain false until the component re-renders
        // So console.log will output `false` again the first time this is called
        console.log(isAuth);
    }, [isAuth]);

    // The first time this is rendered it will output <p>False</p>

    // There will be a re-render after the `setState` call and it will
    // output <p>True</p> 
    return <div>{isAuth ? <p>True</p> : <p>False</p>}</div>;
};

export default Authentication;
🌐
W3Schools
w3schools.com › react › react_useeffect.asp
React useEffect Hooks
Here is an example of a useEffect Hook that is dependent on a variable. If the count variable updates, the effect will run again: import { useState, useEffect } from 'react'; import { createRoot } from 'react-dom/client'; function Counter() { const [count, setCount] = useState(0); const [calculation, setCalculation] = useState(0); useEffect(() => { setCalculation(() => count * 2); }, [count]); // <- add the count variable here return ( <> <p>Count: {count}</p> <button onClick={() => setCount((c) => c + 1)}>+</button> <p>Calculation: {calculation}</p> </> ); } createRoot(document.getElementById('root')).render( <Counter /> );