title: Why is my custom hook called so many times?
body: <p>I'm trying to implement a custom hook to provide the app with a guest shopping cart. My hook wraps around the <code>useMutation</code> hook from Apollo and it saves the shopping cart id in a cookie while also providing a function to "reset" the cart (basically, to remove the cookie when the order is placed).</p>
  
  <p>Code time! (some code omitted for brevity):</p>
  
  <pre><code>export const useGuestCart = () =&gt; {
      let cartId;
      const [createCart, { data, error, loading }] = useMutation(MUTATION_CREATE_CART);
      console.log(`Hook!`);
  
      if (!cartId || cartId.length === 0) {
          createCart();
      }
      if (loading) {
          console.log(`Still loading`);
      }
      if (data) {
          console.log(`Got cart id ${data.createEmptyCart}`);
          cartId = data.createEmptyCart;
      }
  
      const resetGuestCart = useCallback(() =&gt; {
          // function body here
      });
  
      return [cartId, resetGuestCart];
  };
  </code></pre>
  
  <p>In my component I just get the id of the cart using <code>let [cartId, resetCart] = useGuestCart();</code> . </p>
  
  <p>When I run my unit test (using the Apollo  to provide a mock mutation) I see the hooked invoked several times, with an output that looks something like this:</p>
  
  <pre><code>console.log src/utils/hooks.js:53
      Hook!
  
    console.log src/utils/hooks.js:53
      Hook!
  
    console.log src/utils/hooks.js:59
      Still loading
  
    console.log src/utils/hooks.js:53
      Hook!
  
    console.log src/utils/hooks.js:62
      Got cart id guest123
  
    console.log src/utils/hooks.js:53
      Hook!
  
    console.log src/utils/hooks.js:53
      Hook!
  </code></pre>
  
  <p>I'm only getting started with hooks, so I'm still having trouble grasping the way they work. Why so many invocations of the hook?</p>
  
  <p>Thank you for your replies!</p>