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;
}
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;
}
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;
}
3 Replies
bigmistqke
bigmistqke2w ago
You are correct, no createEffect/onMount will run on the server. Afaik your code should also work without the onMount. onMount(...) === createEffect(() => untrack(...)) conceptually speaking
Elipzer
ElipzerOP2w ago
Ahhh, I see. This cleans up a bunch of my conditionals. Thanks!
bigmistqke
bigmistqke2w ago
You are very welcome!

Did you find this page helpful?