Why is my custom hook called so many times?
Asked Answered
P

1

8

I'm trying to implement a custom hook to provide the app with a guest shopping cart. My hook wraps around the useMutation 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).

Code time! (some code omitted for brevity):

export const useGuestCart = () => {
    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(() => {
        // function body here
    });

    return [cartId, resetGuestCart];
};

In my component I just get the id of the cart using let [cartId, resetCart] = useGuestCart(); .

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:

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!

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?

Thank you for your replies!

Pipestone answered 19/9, 2019 at 9:3 Comment(0)
B
3

Think of hooks as having that same code directly in the component. This means that every time the component renders the hook will run.

For example you define:

let cartId;
// ...
if (!cartId || cartId.length === 0) {
    createCart();
}

The content inside the statement will run on every render as cartId is created every time and it doesn't have any value assigned at that point. Instead of using if statements use useEffect:

export const useGuestCart = () => {
    const [cartId, setCartId] = useState(0);
    const [createCart, { data, error, loading }] = useMutation(
        MUTATION_CREATE_CART
    );
    const resetGuestCart = () => {
        // function body here
    };

    useEffect(() => {
        if(!cartId || cartId.length === 0){
            createCart();
        }
    }, [cartId]);

    useEffect(() => {
        // Here we need to consider the first render.
        if (loading) {
            console.log(`Started loading`);
        } else {
            console.log(`Finished loading`);
        }
    }, [loading]);

    useEffect(() => {
        // Here we need to consider the first render.
        console.log(`Got cart id ${data.createEmptyCart}`);
        setCartId(data.createEmptyCart);
    }, [data]);

    return [cartId, resetGuestCart];
};

Also notice that there is no actual benefit from using useCallback if the component which is receiving the function is not memoized.

Boodle answered 19/9, 2019 at 10:10 Comment(1)
Thanks, that was very helpful! I refactored my code and now everything runs smoothly!Pipestone

© 2022 - 2024 — McMap. All rights reserved.