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

Working of `useState` function inside `useEffect` function
I am trying to use useState inside useEffect. More on stackoverflow.com
🌐 stackoverflow.com
August 16, 2019
Bug: setState inside useEffect is unreliable in React 18
When I updated to react 18, there where parts of the code that caused infinite loops. The browser tab ends up frozen and I have to stop javascript in the page to be able to close the tab, and somet... More on github.com
🌐 github.com
17
October 31, 2022
When you're using useState and useEffect at the same time, does useEffect run first before a hook variable is updated?
function App() { const [inputValue, setInputValue] = useState(""); const previousInputValue = useRef(""); useEffect(() => { previousInputValue.current = inputValue; }, [inputValue]); return ( <> setInputValue(e.target.value)} />

Current Value: {inputValue}

Previous Value: {previousInputValue.current}

); } More on reddit.com
🌐 r/reactjs
10
3
June 23, 2023
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
🌐
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
🌐
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.
🌐
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.
🌐
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.
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;
🌐
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 ...
🌐
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 /> );
🌐
GitHub
github.com › facebook › react › issues › 25593
Bug: setState inside useEffect is unreliable in React 18 · Issue #25593 · facebook/react
October 31, 2022 - Bug: state updates are applied out of order inside useEffect when using Promise.resolve #24649 · Bug: Bad state updates with Promise.resolve and useReducer #24650 ... const routeCount = useSelector(selectRouteCount); const [lastRouteCount, setLastRouteCount] = React.useState(routeCount); React.useEffect(() => { const run = async () => { await dispatch(resultInfoListApplyTimeout()); }; if (lastRouteCount < routeCount) { // console.log('lastRouteCount', lastRouteCount, routeCount); setLastRouteCount(routeCount); void handleResult(async () => run()); } }, [routeCount, lastRouteCount, handleResult, dispatch]);
Author   lucasbasquerotto
🌐
Reddit
reddit.com › r/reactjs › when you're using usestate and useeffect at the same time, does useeffect run first before a hook variable is updated?
r/reactjs on Reddit: When you're using useState and useEffect at the same time, does useEffect run first before a hook variable is updated?
June 23, 2023 -

Hello,So I am learning about useRef() and came across this example in w3schools.com

function App() {
const [inputValue, setInputValue] = useState(""); 
const previousInputValue = useRef("");
useEffect(() => { 
previousInputValue.current = inputValue; }
, [inputValue]);

return ( <> 
<input type="text" value={inputValue} onChange={(e) => setInputValue(e.target.value)} /> 

<h2>Current Value: {inputValue}</h2> 

<h2>Previous Value: {previousInputValue.current}</h2> 

</> );}

Or https://www.w3schools.com/REACT/react_useref.asp (sorry; copy and paste is not working correctly and formatting is getting destroyed on reddit smh)

So, whenever someone changes the value in 'text' input tag (which is "synced" to inputValue hook), i can see useEffect() function is called.

now, in this following line, I am surprised that inputValue will have the old value and my understanding was useEffect (with inputValue as dependency) will run once that is updated.

useEffect(() => {
previousInputValue.current = inputValue; 
}, [inputValue]);

Could someone please guide me on why inputValue won't have the latest/newest updated value inside useEffect()?