Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Too many rerenders when I use fetch hook

when I try to fetch data from the server, I have 4 data responses in my web console instead of 1.
This is my code

export default function SelectTableComponent() {
    const { data, isLoading, error } = useFetchCaseStudy();

    console.log(data);

    return (
        <div className="container">
            {isLoading && <div>A moment please...</div>}
            {error && (
                <div>{`There is a problem fetching the get data - ${error}`}</div>
            )}
            {data && <DataGrid
                columns={columns}
                rows={data}
            />}
        </div>
    );
}

export function useFetchCaseStudy(): useFetch.FetchResult<caseStudy[]> {
  const { data, isLoading, error } = useFetch<caseStudy[]>(
    `https://..../case-study`,
  );

  return { data, isLoading, error };
}

I would like to have just one response

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You’re going to see that console.log executed at least twice:

  1. Once when the component first renders (on mount), before the fetch is started
  2. Again when the component re-renders because the fetch completes (either with data or an error) (okay, technically if it never completes you won’t see this, but I’m assuming it completes)

It’s probably repeating that cycle a second time because of StrictMode in development. In StrictMode, certain operations that are supposed to be pure are synthetically repeated (to prove that they’re pure).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading