Home > Net >  Excessive useEffect triggers on hot reload
Excessive useEffect triggers on hot reload

Time:09-13

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.

CodePudding user response:

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 { getReportsData } from 'toolkit/slices';

const terms = defaultTuples[~~(Math.random() * defaultTuples.length)];
const defaultReq = () => {
 store.dispatch(getData({ terms }));
};
defaultReq();

root.render(
 <ErrorBoundary>
  <BrowserRouter>
   <App>
    .............

CodePudding user response:

In Strict Mode, React will call your effects twice in order to help you find accidental impurities. This is development-only behavior and does not affect production. If your effects are pure (as they should be), this should not affect the logic of your component. The result from one of the calls is ignored.

  • Related