I need to run a POST request only once when I enter the page, the purpose is to validate an user, depending on the response, different content will be shown on the page.
I'm using react-query to do the request, here's the example:
const { mutate } = useMutation({
mutationFn: () => axios.post('/api/validate-users').then(res => res.data),
});
useEffect(() => {
mutate({}, {
onSuccess: (data) => {
// Do something based on response data
}
})
}, [])
It works normally without StrictMode, but when it comes in, it makes the API to be called twice, in my use case I can't have this behavior. I read about it in React's documentation, but I can't have this validation attached to a button for example, I need it to run everytime I enter the page.
How can I have this API to be called only once with StrictMode?
I've tried to use React Refs, in order to prevent the API to be called twice. It worked, but it' such a big workaround, I feel like there's something easier to be done.
I know that in prod environment this shouldn't be an issue
The behavior you are experiencing with the API being called twice is related to React's Strict Mode and the double render during development.
React's Strict Mode intentionally triggers two renders for components to help detect potential problems in the application. This can cause issues with some side effects, like making the API call twice in your case. The additional render is meant to catch unintended side effects and help developers identify and fix issues during development.
To make the API call only once, you can use the following approach:
Wrap the useEffect hook inside a useLayoutEffect hook.
useLayoutEffectruns synchronously after all DOM mutations but before the browser paint. This way, you ensure that the effect runs before rendering to the screen.To avoid the second render caused by React's Strict Mode, use a ref to keep track of whether the API call has already been made or not.