T
TanStack15mo ago
foreign-sapphire

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
robust-apricot
robust-apricot15mo ago
You can add an animation using some lib, or use a debounced isPending
robust-apricot
robust-apricot15mo 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.
national-gold
national-gold15mo 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
foreign-sapphire
foreign-sapphireOP15mo ago
Thank you!

Did you find this page helpful?