Home > Software engineering >  React useEffect called twice even with strict mode disabled
React useEffect called twice even with strict mode disabled

Time:01-15

I'm new to React and am working on a simple receipt scanning web app based on AWS (Amplify, AppSync, GraphQL, DynamoDB, S3). I'm using the useEffect hook to fetch data for the user currently logged in, via a GraphQL call, and am noticing duplicate runs of it. At first, there were three calls, after which I read about and disabled Strict Mode. But now, even with Strict Mode disabled, I am seeing two calls.

Debugging reveals that useEffect is called only once if I comment out setWeekly(getTotalFromItems(response)), but even as little as setWeekly() ends up creating duplicate calls.

I've perused Network log.

import WebFont from 'webfontloader';

import React, {
    useEffect,
    useState
} from 'react'

import {
    withAuthenticator,
    Text,
    View
} from '@aws-amplify/ui-react';

import {
    MainLayout
} from './ui-components';

import awsExports from "./aws-exports";
Amplify.configure(awsExports);

function App({signOut, user}) {
    const [weekly, setWeekly] = useState([]);
    
    useEffect(() => {

        WebFont.load({
            google: {
                families: ['DM Sans', 'Inter']
            }
        });

        async function fetchWeekly(queryTemplate, queryVars) {
            try {
                const weeklyData = await API.graphql(graphqlOperation(queryTemplate, queryVars))
                console.log(weeklyData)
                const response = weeklyData.data.getUser.receiptsByPurchaseDateU.items
                const total = getTotalFromItems(response) // sums 'total' in [{'date': '...', 'total': 9}, ...]
                setWeekly(total)
        } catch (err) {
                console.log('Error fetching data.');
                console.log(err)
        }
        }

        const queryVars = {
            username: user.attributes.email,
        }

        let d = new Date();
        d.setDate(d.getDate() - 7);
        d = d.toLocaleDateString('en-CA');
        let tmpl = generateSummaryTemplate(d) // returns a template string based on d
        fetchWeekly(tmpl, queryVars);
        console.log('Complete.')
    });

 return ( <View >
        <MainLayout/>
        </View >
        )
}

export default withAuthenticator(App);

CodePudding user response:

The issue here is that the useEffect hook is missing a dependency array. The useEffect callback enqueues a weekly state update which triggers a component rerender and the useEffect hook is called again. This second time it again computes a value and enqueues a weekly state update. It's this second time that the state is enqueued with the same value as the current state value and React decides to bail on further rerenders. See Bailing out of State Updates.

If you update a State Hook to the same value as the current state, React will bail out without rendering the children or firing effects. (React uses the Object.is comparison algorithm.)

The solution is to add a dependency array with appropriate dependencies. Use an empty array if you want the effect to run once after the initial render when the component mounts. In this case it seems the passed user prop is the only external dependency I see at the moment. Add user to the dependency array. This is to indicate when the effect should run, i.e. after the initial mount/render and anytime user value changes. See Conditionally firing an effect.

Example:

useEffect(() => {
  ...

  async function fetchWeekly(queryTemplate, queryVars) {
    try {
      const weeklyData = await API.graphql(graphqlOperation(queryTemplate, queryVars));
      const response = weeklyData.data.getUser.receiptsByPurchaseDateU.items
      const total = getTotalFromItems(response) // sums 'total' in [{'date': '...', 'total': 9}, ...]
      setWeekly(total);
    } catch (err) {
      console.log('Error fetching data.');
      console.log(err);
    }
  }

  const queryVars = {
    username: user.attributes.email,
  };

  let d = new Date();
  d.setDate(d.getDate() - 7);
  d = d.toLocaleDateString('en-CA');
  let tmpl = generateSummaryTemplate(d); // returns a template string based on d
  fetchWeekly(tmpl, queryVars);
  console.log('Complete.');
}, [user]); // <-- user is external dependency

CodePudding user response:

First of add a dependency array as the second argument to the useEffect, after the callback function. Moreover, I may advice that you have service functions outside the useEffect body, don't overload it like that, is not appropirate.

CodePudding user response:

It’s because setWeekly() is called within your useEffect() and triggers another render. You may remove this useState() entirely and instead return the data you need in fetchWeekly().

  • Related