1

I have a redux-toolkit slice with a 'loading' state value that is initially set to idle.
When dispatching a createAsyncThunk action, the loading state value is updated to pending, and I can observe that the state is updated correctly from the Redux dev tools.
The dispatch is called inside a useEffect with the value from the loading selector in the dependency array. I test that the value is equal to 'idle' before dispatching the action. But somehow, the action is dispatched at least twice (many more times in my code). Why ?
It looks like the selector is not picking up the state change.

Here is a minimal reproducible example sandbox: https://codesandbox.io/s/hungry-sammet-0smieb

Ordinaly
  • 69
  • 1
  • 9

1 Answers1

3

This is the behavior of the StrictMode component.

useEffect(() => {
    if (loading === "idle") {
      console.count(loading);
      dispatch(getSomething());
    }
  }, [loading, dispatch]);

With the StrictMode component, the logs:

idle: 1 
idle: 2 

Without the StrictMode component, the logs:

idle: 1 

Codesandbox

Also see Why is my React component is rendering twice?

Lin Du
  • 88,126
  • 95
  • 281
  • 483