Answer the question
In order to leave comments, you need to log in
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
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.
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.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question