I want to execute a dispatch called loadMe once when rendering for the first time with useEffect in the About component.
However, when the screen is refreshed, the dispatch is executed 4 times. Like the picture blow
How can I run it only once?
this is my code
About.tsx
const About = () => {
const dispatch = useAppDispatch();
useEffect( () => {
const loadMy = async()=> {
dispatch(loadMe());
}
loadMy();
},[]);
return (
<>
<div>About page</div>
</>
);
};
export default About;
Action.tsx
export const loadMe = createAsyncThunk(
'/loadMe',
async ( data, {rejectWithValue}) => {
try {
const userId = await localStorage.getItem('UserId');
return userId;
} catch (error: any) {
console.error(error);
return rejectWithValue(error.response.data);
}
},
);
CodePudding user response:
It is called 4 times because of async and the way react works under the hood.
React Strict Mode
The way react works in development mode is that it runs in strict mode by default. In strict mode all components are rendered twice to aid developer in error checking. So paired with async this makes 4 dispatches in total
Async
With Async functions, they are called initially and return a promise which dispatches the first 2 times causing a render, when the promise is resolved, another re-render happens causing the dispatch to be made again 2 times.