How to prevent useSWR being called multiple times from a customHook that is used in many places. #2886
Replies: 3 comments 1 reply
-
I am guessing the hook is called multiple times depending how you structure your hook calls in those different components. I would suggest calling useSWR() conditionally to confirm if the useSWR() is making multiple calls. |
Beta Was this translation helpful? Give feedback.
-
Please take a read of this page: https://swr.vercel.app/docs/revalidation, especially the "Disable Automatic Revalidations" part. |
Beta Was this translation helpful? Give feedback.
-
This is an excellent question and one I am myself having trouble with, even when using |
Beta Was this translation helpful? Give feedback.
-
I'd appreciate some clarity over how useSWR is supposed to work in respect of the same url being called in different places.
Should it recognise that it's being called multiple times and debounce/cache to only one call?
Essentially I'm trying to create a singleton Cart.
I have custom useCart() hook that contains a useSWR() to fetch the cart data from the backend.
I use this useCart hook in various places including the component on my products.
I was hoping it would only get called once but it seems like it gets called many times since there are multiple buy buttons.
Is my understanding wrong or am I missing a trick? Is there a way to use a hook in multiple places and not trigger SWR being called multiple times? Is it a timing issue?
I'm also using Zustand to store some other state. Is there a way to use useSWR in a zustand store to ensure a singleton
Thanks
Beta Was this translation helpful? Give feedback.
All reactions