1. This is happening because due to the fact that you're using a part of the Redux state (i.e. the posts which you extract from Redux store using useSelector), your component will automatically re-render when the state changes.

  2. However, each time you are mounting your component, you are also calling the dispatch method in your useEffect that changes the Redux store and causes your component to re-render.

  3. Again, during the re-render, your useEffect runs the dispatch function that causes a Redux store update which in turn causes yet another re-render and this is how you've gotten caught up in an infinite loop of re-renders and Redux store updates

  4. A solution to this might be to only run dispatch only when the payload changes by running the useEffect exclusively when payload changes and not when component mounts

  5. You can use the following code for the same :

useUpdateEffect - custom react hook that will only run when dependencies change

import { useEffect, useRef } from "react"

export default function useUpdateEffect(callback, dependencies) {
  const firstRenderRef = useRef(true)

  // Since ref persists value between renders (and itself doesn't trigger a render when value is changed), we can simply just set ref to a failing condition on our 1st render so that component only is re-rendered when dependencies change and not also "onMount"
  useEffect(() => {
    if (firstRenderRef.current) {
      firstRenderRef.current = false
      return
    }
    return callback()
  }, dependencies)
}

Using the useUpdateEffect hook in our code :

  const dispatch = useDispatch();

  useUpdateEffect(() => {
    dispatch(fetchPostsByTerm(payload));  
  }, [payload])

  const posts = useSelector((state) => state.postsByTerm);

  return (
    <div>
      <h1 className="post_heading">Posts</h1>
      {posts ? posts.map((post) => <h1>{post.entityLable}</h1>) : <h1>no posts</h1>}
    </div>
  );
};

Answer from Ankit Sanghvi on Stack Overflow
🌐
GitHub
github.com › reduxjs › react-redux › issues › 2160
Unstable selectors causes infinite loop in React · Issue #2160 · reduxjs/react-redux
April 25, 2024 - due to internal implementation of useSyncExternalStore - stability MUST BE enforced, or React can enter endless loops due to various but yet unknown reasons. useSelector dont have any extra caching layers, and yet the necessity to enforce stability ...
Author   theKashey
Top answer
1 of 2
1
  1. This is happening because due to the fact that you're using a part of the Redux state (i.e. the posts which you extract from Redux store using useSelector), your component will automatically re-render when the state changes.

  2. However, each time you are mounting your component, you are also calling the dispatch method in your useEffect that changes the Redux store and causes your component to re-render.

  3. Again, during the re-render, your useEffect runs the dispatch function that causes a Redux store update which in turn causes yet another re-render and this is how you've gotten caught up in an infinite loop of re-renders and Redux store updates

  4. A solution to this might be to only run dispatch only when the payload changes by running the useEffect exclusively when payload changes and not when component mounts

  5. You can use the following code for the same :

useUpdateEffect - custom react hook that will only run when dependencies change

import { useEffect, useRef } from "react"

export default function useUpdateEffect(callback, dependencies) {
  const firstRenderRef = useRef(true)

  // Since ref persists value between renders (and itself doesn't trigger a render when value is changed), we can simply just set ref to a failing condition on our 1st render so that component only is re-rendered when dependencies change and not also "onMount"
  useEffect(() => {
    if (firstRenderRef.current) {
      firstRenderRef.current = false
      return
    }
    return callback()
  }, dependencies)
}

Using the useUpdateEffect hook in our code :

  const dispatch = useDispatch();

  useUpdateEffect(() => {
    dispatch(fetchPostsByTerm(payload));  
  }, [payload])

  const posts = useSelector((state) => state.postsByTerm);

  return (
    <div>
      <h1 className="post_heading">Posts</h1>
      {posts ? posts.map((post) => <h1>{post.entityLable}</h1>) : <h1>no posts</h1>}
    </div>
  );
};

2 of 2
-1

just write dispatch in dependency array like this [dispatch]

Discussions

reactjs - Strange problems with useEffect and useSelector cause infinite loops - Stack Overflow
That's correct, but data is being changed: the useSelector function is returning a new list each time your component is rendered, and in JavaScript, two lists aren't considered equal just because they currently contain the same elements. The reason your effect is triggering an infinite loop is that ... More on stackoverflow.com
🌐 stackoverflow.com
January 17, 2024
react native - Infinite loop with useEffect hook with useSelector - Stack Overflow
The logic in the useSelector just converts the byId object into an array. The infinite looping occurs when I set the categories array as a dependency: More on stackoverflow.com
🌐 stackoverflow.com
reactjs - useEffect goes in infinite loop when combined useDispatch, useSelector of Redux - Stack Overflow
getProduct is receives value from function useSelector of react-redux 2019-09-13T15:31:09.457Z+00:00 ... show a complete example if you want better help. It is hard to guess where your infinite loop is coming from with only a snippet of code 2019-09-13T15:50:36.077Z+00:00 More on stackoverflow.com
🌐 stackoverflow.com
September 13, 2019
getting infinite loop when using useSelector value inside useEffect
Info => i am fetching data from backend, the reducer value "currentUser" null before it gets the data from database. As soon as i get the data i am initializing it useState() in my More on stackoverflow.com
🌐 stackoverflow.com
June 3, 2021
🌐
GitHub
github.com › reactjs › rfcs › issues › 123
useEffect goes in infinite loop when combined useDispatch, useSelector of Redux · Issue #123 · reactjs/rfcs
September 12, 2019 - const { history, match } = props; const getProduct = useSelector(state => state.itemEditing); const dispatch = useDispatch(); const { values, setValues, handleChange, handleSubmit } = useForm( getProduct, history ); useEffect(() => { if (match) { let id = match.params.id; dispatch(actGetProductRequest(id)); } setValues(()=>({...getProduct})); },[match,dispatch, setValues, getProduct]);
Top answer
1 of 2
1

My understanding of useEffect monitoring should be that when the data is changed, he will re-execute the code in useEffect.

Your understanding of the useEffect hook is correct, but you are not understanding that your useSelector hook is potentially returning a new array object reference each time the component renders. In other words, data is a new reference that triggers the useEffect hook to run. The useEffect hook enqueues a list state update. When React processes the list state update it triggers a component rerender. data is selected and computed from the Redux store. Repeat ad nauseam.

You can help break the cycle by using an equality function with the useSelector hook. See Equality Comparisons and Updates.

import { shallowEqual, useSelector } from 'react-redux';

...

const data = useSelector((state: DeviceList) => {
  if (state.basicSetting !== null) {
    return state.basicSetting.filter(
      item =>
        item.deviceName.includes('ac') &&
        !item.deviceName.includes('bz'),
    );
  } else {
    return null;
  }
}, shallowEqual); // <-- shallow equality instead of strict equality

Another good solution is to create a memoized selector function from Reselect, and since you are using Redux-Toolkit, createSelector is re-exported from Reselect. (Reselect is maintained by the same Redux/Redux-Toolkit developers)

It allows you to write the same computed data value but it memoizes the result so that if the selected state going into the selector hasn't changed, then the selector returns the same previously computed value. In other words, it provides a stable returned data value that will only trigger the useEffect when state actually updates and the selector computes a new value reference.

However, it is a bit unclear why you are selecting state from the store and duplicating it locally into state. This is generally considered a React anti-pattern. You can compute the list value directly from the store.

Example:

const list = useSelector((state: DeviceList) => {
  if (state.basicSetting === null) {
    return null;
  }
  
  const data = state.basicSetting.filter(
    item =>
      item.deviceName.includes('ac') &&
      !item.deviceName.includes('bz'),
  ) as DeviceDataOne[];

  const list: DeviceDataOne[] = [];
  while (data.length) {
    list.push(data.splice(0, 4));
  }
  return list;
});

useEffect(() => {
  console.log('list', list);
}, [list]);
2 of 2
0

My understanding of useEffect monitoring should be that when the data is changed, he will re-execute the code in useEffect.

That's correct, but data is being changed: the useSelector function is returning a new list each time your component is rendered, and in JavaScript, two lists aren't considered equal just because they currently contain the same elements.

The reason your effect is triggering an infinite loop is that it changes the list state every time, which triggers a new render, which changes data, which triggers the effect again.

🌐
Stack Overflow
stackoverflow.com › questions › 67825070 › getting-infinite-loop-when-using-useselector-value-inside-useeffect
getting infinite loop when using useSelector value inside useEffect
June 3, 2021 - Problem => Whenever i try to check if there is data inside the reducer value, it gives me infinite loop. ... const currentUser = useSelector((state) => state.userReducer.currentUser); const [userInfo, setUserInfo] = useState({ name: "", email: "", }); useEffect(() => { dispatch(getCurrentuserAction(user?.result?.email)); if (currentUser) setUserInfo(currentUser); }, [currentUser, dispatch, user?.result?.email]); //Here is issue
Find elsewhere
🌐
GitHub
github.com › reduxjs › react-redux › issues › 1310
`useSelector` comparator swallows errors · Issue #1310 · reduxjs/react-redux
June 11, 2019 - Your bug will get fixed much faster if we can run your code and it doesn't have dependencies other than React. Paste the link to a CodeSandbox (https://codesandbox.io/s/new) or RN Snack (https://snack.expo.io/) example below: https://codesandbox.io/s/redux-useselector-comparator-bug-ho0e4
Author   migueloller
🌐
YouTube
youtube.com › watch
How to Prevent an Infinite Loop in React's useEffect with useSelector - YouTube
Discover the common pitfall of `infinite loops` in React when using `useEffect` with `useSelector`, and learn the simple solution to fix it!---This video is ...
Published   March 30, 2025
Views   0
🌐
YouTube
youtube.com › watch
How to Fix the Infinite Loop Issue in React's UseEffect with UseSelector and UseDispatch - YouTube
Learn how to resolve the infinite loop problem in your React application when using useEffect with Redux. Simplify your state management and fix your compone...
Published   April 1, 2025
Views   0
🌐
GitHub
github.com › statelyai › xstate › discussions › 3379
How to render an array of actors selected using `useSelector`? · statelyai/xstate · Discussion #3379
And in the component where I want to render the list of actors, I use useSelector to select the list of actor references from the context of the machine. I then map them, render a list, pass the actor ref to the component, and use useActor to tap into the state of the actor reference, sample sandbox actor-array. Everything is working as expected, except I get a warning in the console that the result of getSnapshot should be cached to avoid an infinite loop.
Author   statelyai
🌐
Reddit
reddit.com › r/reactjs › how do i access the latest value of state using useselector after dispatching an action in redux?
r/reactjs on Reddit: How do I access the latest value of state using useSelector after dispatching an action in redux?
February 21, 2020 -

Really sorry if this isn't the place to ask, I just thought if anyone would know it's someone on here 😊

I have a screen in a React-Native project which essentially just renders a loading icon whilst fetching data from the server, before then taking the user to the main screen. The first function getPrivateKey() will return the private key and store it using redux in the state, and the next function connectWithKey() will then use that key to connect.

The issue I'm facing is that when connectWithkey() runs, it's using the initial, empty value of the private key, not the updated value. Here's the code, and apologies if I'm being stupid it's been a long day :(

export default DataLoader = props => {
  //private key - this should, in theory, update after getPrivateKey()
  const privateKey = useSelector(({ main }) => main.privateKey);
  const dispatch = useDispatch();

  useEffect(() => {
    const configure = async () => {
      //this will update the private key
      await getPrivateKey();

      //this should use the new private key from useSelector, but instead is using 
     //the initialised empty object
     await connectWithKey();

      props.navigation.navigate('MainScreen');
    };
    configure();
  }, []);

//.... more code below....

I've tried adding privateKey into the array dependencies which just caused an infinite loop, and I've checked that the value has updated in the redux store - so I'm a bit lost! In essence, it appears that the useSelector hook isn't getting a fresh value. Any help would be very much appreciated 😊 Thanks!

🌐
CopyProgramming
copyprogramming.com › howto › infinite-loop-with-useeffect-hook-with-useselector
Endless cycle caused by the combination of useEffect and useSelector hooks - React native
May 11, 2023 - The useSelector code essentially transforms the byId item into an array. When I make the categories array a dependency, the infinite loop ing takes place.
🌐
Reddit
reddit.com › r › reactjs › comments › cjosxu › how_would_i_go_about_using_redux_hooks_to_call_an
r/reactjs - How would I go about using Redux Hooks to call an action when my page renders?
February 12, 2021 -

I am trying to do something similar to componentDidMount and call getData action when the page renders. I cannot figure how to do this with Redux Hooks. If I uncomment getUser(userId); it will do an infinite loop.

import React, { useEffect } from 'react';
import { connect, useSelector, useDispatch } from 'react-redux';
import { getData, getUserId } from '../../actions';

import './homepage.scss';

const Main = props => {
const dispatch = useDispatch();

const userId = { auth0_user_id: localStorage.getItem('user_id') };
const user = useSelector(store => store.getUser.user);

console.log(userId);
console.log(user);

const getUser = user => dispatch(getUserId(user));

// getUser(userId);

const logout = e => {
localStorage.removeItem('access_token');
localStorage.removeItem('id_token');
localStorage.removeItem('expires_at');
localStorage.removeItem('user_id');
props.history.push('/login');
};

return (
<div>
<h1>Welcome to a Protected Page!</h1>
{props.users
? props.users.map(user => (
// map over the state of users
<h3>{user.auth0_user_id}</h3>
))
: null}
<button onClick={logout}>Log Out</button>
</div>
);
};

export default Main;
🌐
Dmitri Pavlutin
dmitripavlutin.com › react-useeffect-infinite-loop
How to Solve the Infinite Loop of React.useEffect()
February 26, 2023 - The infinite loop is fixed with correct management of the useEffect(callback, dependencies) dependencies argument.
🌐
Debugcn
debugcn.com › en › article › 40190365.html
Infinite loop useEffect with useSelector - DebugCN
Okay, I figure it out, one of my types in the Reducer rested de inscriptions to and empty array, so it was re-rendering infinitely.