T
TanStack12mo ago
like-gold

Delay isPending render

Typical code:
if(isPending) return (<LoadingSpinner />
if(isPending) return (<LoadingSpinner />
If my query is fast, this results in some flashing (imagine skeletons etc.) I was wondering if some of you did some sort of delay (like 0.1s) before rendering the skeleton). How did you do it? This could have these advantages: no flashing, no unnecessary render, better accessibility.
4 Replies
rare-sapphire
rare-sapphire12mo ago
You can add an animation using some lib, or use a debounced isPending
rare-sapphire
rare-sapphire12mo ago
You can use https://usehooks.com/usedebounce for the debounce. Just use const debouncedIsPending = useDebounce(isPending, 500). This way debouncedIsPending can update at most once every 500 ms
useDebounce React Hook – useHooks
Delay the execution of function or state update with useDebounce.
harsh-harlequin
harsh-harlequin12mo ago
import { useState, useEffect } from "react";

export const useDebouncedTrue = (bool, timeMs) => {
const [internalBool, setInternalBool] = useState(bool);

useEffect(() => {
let timeout = null;

if (bool) setInternalBool(true);
else timeout = setTimeout(() => setInternalBool(false), timeMs);

return () => clearTimeout(timeout);
}, [bool, timeMs]);

return internalBool;
};
import { useState, useEffect } from "react";

export const useDebouncedTrue = (bool, timeMs) => {
const [internalBool, setInternalBool] = useState(bool);

useEffect(() => {
let timeout = null;

if (bool) setInternalBool(true);
else timeout = setTimeout(() => setInternalBool(false), timeMs);

return () => clearTimeout(timeout);
}, [bool, timeMs]);

return internalBool;
};
or implement your own, this starts a timeout to set false everytime bool becomes false, but lets true through and clears the timeout
like-gold
like-goldOP12mo ago
Thank you!

Did you find this page helpful?