'Debounce library hook of a lib that make API call on React

I'm using a library that connect to a client with a provider and offer an hook that make an API call and returns some data (similar to react-query).

Sometimes happen that some parents components, of the component where I use that hook, refresh their state so the hook called and then it make a lot of API calls.

I can't modify the library hook and I can't create nested hooks (react standard rules) so how can I debounce an hook that make an API call? Is there a way to do this?

Example:

Using Chakra UI hook useBreakpointValue and resizing the window (for example dragging console) the component refresh and the useAPI is recalled a lot of time.

function ParentComponent() {
    const mode = useBreakpointValue({base: false, lg: true});
    return <Component mode={mode} />;
}

function Component({mode}) {
  const {data, isLoading} = useAPI(); // Need to be debounced

  if(isLoading) return <Loader />;
  return (<div>{data.result.map((row) => <Row item={row} mode={mode} />)}</div>)  
}



Solution 1:[1]

You can use SWR library or React.memo

function ParentComponent() {
    const mode = useBreakpointValue({base: false, lg: true});
    return <Component mode={mode} />;
}

const Component = React.memo(function({mode}) {
  const {data, isLoading} = useAPI(); // Need to be debounced

  if(isLoading) return <Loader />;
  return (<div>{data.result.map((row) => <Row item={row} mode={mode} />)}</div>)  
})

Or in SWR https://swr.vercel.app/

const { data, error } = useSWR(
    "uniq key of this request",
    ()=>useAPI().data
  );


  if(!data) return <Loader />;
  return (<div>{data.result.map((row) => <Row item={row} mode={mode} />)}</div>) 

Sources

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

Source: Stack Overflow

Solution Source
Solution 1