skip to Main Content

I’m encountering an issue in my React application where the fetch function inside a useEffect hook is being called twice, and I’m struggling to understand why. Here’s the relevant code:

useEffect(() => {
    if (auth.userDTO && router.isReady) {
        let url = paymentId ? `user/tickets?paymentId=${paymentId}` : 'user/tickets';
        fetchWithBaseUrl(url, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                Authorization: 'Bearer ' + auth.userDTO.token,
            },
        }).then(async (response) => {
            if (response.ok) {
                const data = await response.json();
                setMyTickets(data);
            }
        });
    }
}, [auth.userDTO, router.isReady]);

As you can see, I’ve defined auth.userDTO and router.isReady as dependencies for the useEffect. However, I’ve noticed that the fetch function is being called twice under certain circumstances.

I’ve considered the following:

  1. Initial Render: The fetch function is called on the initial render, which is expected behavior.
  2. Dependency Changes: If either auth.userDTO or router.isReady changes during the component’s lifecycle, the useEffect hook runs again, leading to an additional call to fetch.
    I’m wondering if there’s a way to prevent the extra call to fetch while still ensuring that it runs when both auth.userDTO and router.isReady are truthy.

Has anyone encountered a similar issue, and if so, how did you resolve it? Are there any best practices or optimizations I can apply to avoid this behavior?

2

Answers


  1. If React is in dev mode, it will most probably be using Strict Mode, like this:

      <StrictMode>
        <App />
      </StrictMode>
    

    In Strict Mode, useEffect’s will run twice on first render.

    This article also gives more info on strict mode and how to disable it if you do not want the useEffects to run twice.

    Login or Signup to reply.
  2. It fetches twice because you most likely are using react dev tools, which does make it happen twice.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search