Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 39 ยท Resources, Suspense and Async

Async Patterns: Debounce, Optimistic Updates, Polling

Practical async recipes for SolidJS: debounce a search signal, cancel stale work with onCleanup, update the UI optimistically with rollback, and poll safely.

You know how to load data with createResource and show it with Suspense. Real interfaces need a few extra habits: do not fire a request on every keystroke, do not let an old answer overwrite a new one, make clicks feel instant, and refresh data on a timer without leaking intervals.

Each recipe below is small and built from primitives you already know: signals, effects, onCleanup and mutate.

Debouncing a signal

Typing "solid" into a search box changes the signal five times in a second. Searching on each change wastes requests. A debounced signal follows the original but only updates after it has been quiet for a while.

JavaScript
import { createSignal, createEffect, onCleanup } from "solid-js";

export function createDebounced(source, delay = 300) {
  const [value, setValue] = createSignal(source());
  createEffect(() => {
    const next = source();                       // tracked
    const timer = setTimeout(() => setValue(() => next), delay);
    onCleanup(() => clearTimeout(timer));        // runs before the next run
  });
  return value;
}

The important line is onCleanup. It runs before the effect re-runs and when the owner is disposed. Each new keystroke clears the previous timer, so only the last one fires. (setValue(() => next) uses the updater form so a function-valued source cannot be misread as an updater.)

Debounced search

Type "sig" quickly: "Typed" updates on every key while "Searched" waits, and only one request is sent. The || null makes an empty query skip fetching entirely, a trick from the resource lesson.

Cancelling stale work

Resources already ignore answers from outdated requests, so state never goes backwards. But the network request still runs to the end. For expensive calls, cancel it with an AbortController, aborted from onCleanup:

JavaScript
createEffect(() => {
  const q = query();
  const controller = new AbortController();
  onCleanup(() => controller.abort());       // runs when q changes again

  fetch(`/api/search?q=${encodeURIComponent(q)}`, { signal: controller.signal })
    .then((r) => r.json())
    .then(setResults)
    .catch((e) => { if (e.name !== "AbortError") setError(e); });
});

Always filter out AbortError: aborting is not a failure. The same onCleanup pattern works for WebSocket connections, event listeners on window, and intervals.

Optimistic updates

A like button that waits 500 ms for the server before changing feels broken. An optimistic update changes the UI first, sends the request, and rolls back if it fails. A resource's mutate makes this direct:

  1. Remember the old value.
  2. mutate to the expected new value.
  3. Send the request. On failure, mutate back to the old value and tell the user.
Optimistic like with rollback

Click Like: the number rises immediately, long before the "server" answers. Press "Make the next like fail" and click again: the number rises, then drops back after a second with a message. Real apps often use actions with useSubmission for the same idea; the logic is identical.

Polling safely

Refreshing data every few seconds needs an interval that is always cleaned up:

JavaScript
import { createResource, onCleanup } from "solid-js";

const [status, { refetch }] = createResource(fetchStatus);
const timer = setInterval(refetch, 5000);
onCleanup(() => clearInterval(timer));

Without onCleanup, navigating away would leave the interval running and refetching for a component that no longer exists. Because refetch keeps old data visible while loading (refreshing), the UI does not flicker. Consider pausing when the tab is hidden by checking document.hidden.

Avoiding request waterfalls

If component B waits for component A to render before starting its own fetch, the requests run one after another. Start independent fetches together at the same level, or lift them into a route query that starts before rendering (route data). And when one fetch really depends on another, express it with a source signal so Solid chains them for you:

JavaScript
const [user] = createResource(fetchUser);
const [posts] = createResource(() => user()?.id, fetchPostsFor);  // waits for user

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does a debounce effect call onCleanup(() => clearTimeout(timer))?

    Cleanup runs before the next execution, so only the timer from the latest change survives.
  2. 2. What is an optimistic update?

    The UI assumes success for instant feedback and restores the old value on failure.
  3. 3. Why filter AbortError in the catch handler?

    You aborted the request yourself, so showing an error message would be misleading.
  4. 4. What goes wrong if a polling interval has no onCleanup?

    Intervals live outside Solid, so without cleanup they leak and keep running.

Summary

  • Debounce by delaying a signal inside an effect and clearing the timer with onCleanup.
  • Use onCleanup with AbortController to cancel in-flight requests; ignore AbortError.
  • Optimistic UI: save the old value, mutate, call the server, roll back on failure.
  • Always clean up intervals and listeners; chain dependent fetches with a source signal.

Next: SolidStart Overview