SolidJSS
SolidJSโ€ข4mo agoโ€ข
4 replies
Elipzer

Guidance on isServer vs onMount

I've got this utility function to create a debounced signal. From the server-side, I don't want to be setting timeouts. My first approach used isServer, but I also found that putting createEffect inside of an onMount gave similar behavior. Which of these is the most "solid"? Or maybe I shouldn't worry about this at all since I have the onCleanup?

isServer version:
export function createDebounced<T>(value: Accessor<T>, delay: number): Accessor<[T, number]> {
    const [debounced, setDebounced] = createSignal<[T, number]>([value(), 0]);
    createEffect(() => {
        if (isServer) return; // avoiding setting timeout on server-side
        const val = value();
        const timeoutId = setTimeout(() => setDebounced(([_, prevUpdate]) => [val, prevUpdate + 1]), delay);
        onCleanup(() => clearTimeout(timeoutId));
    });
    return debounced;
}


onMount version:
export function createDebounced<T>(value: Accessor<T>, delay: number): Accessor<[T, number]> {
    const [debounced, setDebounced] = createSignal<[T, number]>([value(), 0]);
    onMount(() => {
        createEffect(() => {
            const val = value();
            const timeoutId = setTimeout(() => setDebounced(([_, prevUpdate]) => [val, prevUpdate + 1]), delay);
            onCleanup(() => clearTimeout(timeoutId));
        });
    });
    return debounced;
}
Was this page helpful?