N
N
nskaskyo2021-07-05 14:21:44
React
nskaskyo, 2021-07-05 14:21:44

Hook useRequest/useFetch how to get rid of extra renders?

Here is an absolutely standard hook from the Internet.
The problem with it is that it renders 3 times.
(the first when mounting, the second when changing the Date state and the third when changing the Loading state)

Help me figure out how to remove one of the renderers and make it look beautiful.
Thanks

.

import { useState, useCallback, useEffect } from 'react';

export function useRequest(request) {
    const [data, setData] = useState(null);
    const [isLoading, setIsLoading] = useState(true);
    const [error, setError] = useState(null);

    const execute = useCallback(() => {
        return request()
            .then((response) => setData(response))
            .catch((error) => setError(error))
            .finally(() => setIsLoading(false));
    }, [request]);

    useEffect(() => {
        execute();
    }, [execute]);

    return { data, isLoading, error };
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
P
ParaBellum577, 2021-07-05
@ParaBellum577

If you don’t want extra rendering, move the logic into actions, take data directly from Redux, for example.
If you don’t need a render after you change the state, then don’t use the state at all, you can put the value in useRef, but then the component will not know about the data change in it, I think you don’t need this. In general, 3 renders is quite normal for such a case.

I
Igor Timoshenkov, 2021-07-05
@t1gor

You can also try useLayoutCallback - it is executed synchronously and then even despite your 2 setState in the request handler, the render should be only 1.

A
Aetae, 2021-07-05
@Aetae

Use one state for everything. Update loading value along with data.
Well, it’s better to immediately use something bold and good support for the react-query type , so as not to mess around with your bicycles later.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question