DEV Community

Cover image for Avoid multiple API call on Tab switching in short time span
Sarvesh Patil
Sarvesh Patil

Posted on

Avoid multiple API call on Tab switching in short time span

I have pure component Tabs and rendering 3 child Tab component as a children and every child tab have individual API call integrated to load data into the Grid, So there is server timeout if someone switch tab multiple time in short time span. So can you please suggest best way to reduce API calls.

Top comments (2)

Collapse
 
trunghieu99tt profile image
Trung Hieu Nguyen • Edited

You can add a setTimeout in useEffect and clear that timeout using clean up function. So that you can make sure to call API only when users "stay" on that component for an amount of time. Hope this helps
Something like this:

useEffect(() => {
    const timeout = setTimeout(() => {
        // call api
    }, 5000); // 5 seconds

    return () => {
        clearTimeout(timeout);
    };
}, []);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
sarveshpatil profile image
Sarvesh Patil

thanks man!, Hope it may helps me.