reactjsreact-hooksredux-toolkithot-reload

Excessive useEffect triggers on hot reload


Environment: React18, redux-toolkit (createAsyncThunk), no StrictMode.

I have useEffect in App.tsx of my application. App.tsx is a child of index.tsx where store defined.

  useEffect(() => {
   const defaultTerms = defaultTuples[~~(Math.random() * defaultTuples.length)];
   dispatch(getData({ terms: defaultTerms })
  );
}, [dispatch]);

It pick 2 random words and run createAsyncThunk, get data by this words and set this data and 2 words to store. As i want this action be done only once - this useEffect have no dependencies (only dispatch is dep for this useEffect).

Everything works fine during normal app usage, but during development (hot reload) every code change (in file where useEffect was defined) run this useEffect and add more and more words/data for them to store. I'm looking for a way to awoid this behaviour.


Solution

  • I tried to move this initial request out of App component but got same behaviour. Looks like React completely destroy this file and tree below, but as store initialized above this component, store remembers old values so we are adding there exccess data.

    As a solution for now: i moving this initial request to src/index.tsx and do it out of component

    import { store } from 'toolkit/store';
    import { getData } from 'toolkit/slices';
    
    const data = defaultTuples[~~(Math.random() * defaultTuples.length)];
    const defaultReq = () => {
     store.dispatch(getData({ data }));
    };
    defaultReq();
    
    root.render(
     <ErrorBoundary>
      <BrowserRouter>
       <App>
        .............