'Avoid multiple network calls with hooks and Apollo

I have a hook that makes an Graphql call

export const useGetStuff = (options?: QueryHookOptions<GetStuffResponse, GetStuffQueryArgs>) => {
    const [stuffId] = useStuffId();

    return useQuery<GetStuffResponse, GetStuffQueryArgs>(getStuff, {
        variables: { stuffId },
        notifyOnNetworkStatusChange: true,
        skip: !stuffId,
        ssr: false,
        ...options,
    });
};

And I am using this hook in one another hook

const useCustomHook = () => {
    // some unrelated stuff
    const { data: stuffData, loading } = useGetStuff();
   
    // do logic with stuffData and other unrelated stuff

    return { someProperty };
    
}

and in some component, I am using both useGetStuff and useCustomHook.

const MyComponent = () => {
    const { someProperty } = useCustomHook();
    const { data ,loading } = useGetStuff();

    // stuff
    
}

This implementation causes the getStuff query to be called twice (two network calls).

Is there a simple way to avoid that without having to keep useGetStuff only in the custom hook, since this latter should not have to be returning the stuffData.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source