Skip to content

Commit 10ef04c

Browse files
dananjohnsonzdavis
authored andcommitted
[B] Use ref rather than state for useFetch count
The triggerFetchData callback was calling setState, which beginning in React 18 triggers a re-render when used with renderToString. That meant every component that called useFetch on the server experienced a double render. This commit eliminates the extra render by using useRef rather than useState to track the count.
1 parent 5062e7f commit 10ef04c

File tree

1 file changed

+3
-3
lines changed

1 file changed

+3
-3
lines changed

client/src/hooks/api/useFetch/index.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ export default function useFetch({
3131
const firstRun = useRef(true);
3232
const uid = `fetch_${useUID()}`;
3333
const [requestKey] = useState(options.requestKey ?? `fetch_${useUID()}`);
34-
const [count, setCount] = useState(1);
34+
const count = useRef(1);
3535
const store = useStore();
3636
const getState = store.getState;
3737
const dispatch = useDispatch();
@@ -48,7 +48,7 @@ export default function useFetch({
4848

4949
const [apiCall, ...apiCallArgs] = request;
5050

51-
if (count > 25)
51+
if (count.current > 25)
5252
throw new Error(
5353
`useFetch tried to fetch data more than 25 times. This suggests that an input to
5454
useFetch needs to be memoized.`
@@ -58,7 +58,7 @@ export default function useFetch({
5858
const triggerFetchData = useCallback(() => {
5959
if (!condition) return Promise.resolve();
6060
log("useFetch", requestKey);
61-
setCount(count + 1);
61+
count.current += 1;
6262
const apiFetch = apiCall(...apiCallArgs);
6363
const action = entityStoreActions.request(apiFetch, requestKey, options);
6464
const { promise } = dispatch(action);

0 commit comments

Comments
 (0)