Using "useMutation" hook inside useEffect renders component multiple times (4 times)

ABC component renders multiple time ( 4 times).

i am using custom hooks. In custom hooks all we are doing is using “useMutation” from apollo client and calling the “mutation” function provide by “useMutation” inside useeffect.

Problem: As per my knowledge react renders initially and in each subsequent call of setting state value.

So why is it not rendering only 2 times… why is it rendering 4 times?

am i missing something, Is there some return statement i can call for “useMutation” ??

my code:

import useStripeInitializePublishableKey from "../hooks/useStripeInitializePublishableKey";

const ABC = () => {
  console.log("ABC :: loading....");

  const [paymentGatewayPubKey, pubKeyLoading, pubKeyError] =
    useStripeInitializePublishableKey();

  return (
   <>
    <Text>hello world</Text>  
   </>   
  );
};

export default ABC;

file: useStripeInitializePublishableKey.js

import { useEffect, useState } from "react";
import { useMutation } from "@apollo/client";
import { GET_PAYMENT_GATEWAY_PUB_KEY } from "@api/graphql_api";
const useStripeInitializePublishableKey = () => {
  const [paymentGatewayPubKey, setPaymentGatewayPubKey] = useState("");

  const [
    getPaymentGatewayPubkey,
    { data: pubKeyData, loading: pubKeyLoading, error: pubKeyError },
  ] = useMutation(GET_PAYMENT_GATEWAY_PUB_KEY);

  useEffect(() => {
    getPaymentGatewayPubkey({
      variables: {
        paymentMethodTypes: ["card"],
      },
    });
  }, []);

  useEffect(() => {
    if (pubKeyData) {
      setPaymentGatewayPubKey(
        pubKeyData.get_stripe_publishable_key.publishable_key
      );
    }
  }, [pubKeyData]);

  return [paymentGatewayPubKey, pubKeyLoading, pubKeyError];
};

export default useStripeInitializePublishableKey;

Hi @rosnk :wave: I’m not an expert in React render cycles but I’ll try to list what I think triggers each render in your code:

  1. Initial render of ABC
  2. First useEffect fires, triggering getPaymentGatewayPubkey, which causes a rerender (pubKeyLoading updated)
  3. (and maybe 4?) Once pubKeyData and pubKeyLoading are updated, another render is triggered. On that render, the first useEffect is called again. The getPaymentGatewayPubkey call may or may not be deduplicated, not sure what’s under the hood there since this may be an idempotent operation. pubKeyLoading may update in that time? The second useEffect is also called, which calls setPaymentGatewayPubKey. Since that’s a state update, this is a rerender.

Without being able to run your code, that’s my guess as to what might be going on. I hope that moves the conversation ahead!