DEV Community


Posted on


A Custom React Hook that handles duplicate API call

Today, we are going to create a custom hook that solve this problem:

  • We have multiple components that calling same API.
  • Component may not always be on same page, therefore, they have to call the API by themselves.

Here is a example hook I think can handle this problem:

let isCalling = new Map(); // This can be replace by some global state. I use this for the sake of simplicity.
function useFetch(url) {
  const [data, setData] = useState("");
  useEffect(() => {
    let isThisAPICalling = isCalling.get(url);
    if (!isThisAPICalling) {
      isThisAPICalling = fetch(url).then((response) => response.json());
      isCalling.set(url, isThisAPICalling);
      // The body can only be parsed once.
    isThisAPICalling.then((json) => {
  }, []);
  return data;
Enter fullscreen mode Exit fullscreen mode

Here is a demo.

Thank you all! Please let me know if you have any suggestion.

Top comments (2)

alfredosalzillo profile image
Alfredo Salzillo

Maybe you wanted to implement an useDebounce

GitHub logo xnimorz / use-debounce

A debounce hook for react



yarn add use-debounce
# or
npm i use-debounce --save
Enter fullscreen mode Exit fullscreen mode


The simplest way to start playing around with use-debounce is with this CodeSandbox snippet

More complex example with searching for matching countries using debounced input: (thanks to


Simple values debouncing

According to

import React, { useState } from 'react';
import { useDebounce } from 'use-debounce';
export default function Input() {
  const [text, setText] = useState('Hello');
  const [value] = useDebounce(text, 1000);
  return (
        onChange={(e) => {
      <p>Actual value: {text}</
Enter fullscreen mode Exit fullscreen mode
anxiny profile image

Thanks for replying.

But I feel like this is for the function that is repeatly called in one component.
Here is multiple components calling same api.

The 25 most recommended programming books of all-time

  • The post lists the 25 most recommended programming books of all time
  • The list is based on recommendations from programmers around the world
  • The books cover a range of topics including software design, algorithms, programming languages, and more
  • Classics like "The Pragmatic Programmer" and "Design Patterns" are included
  • Newer favorites like "Clean Code" and "The Phoenix Project" are also on the list