Skip to content

Writing Portable Hooks

How-to Guide2 min read
Edit page

You will extract reactive business logic into hook functions that know nothing about the view framework. This is the core Quoin workflow: hooks depend only on the ReactiveContext and Signal traits, so the same function serves GPUI, Leptos, Dioxus, Xilem, and Floem.

Prerequisites: Quoin installed with one framework feature (see Installation).

Write hooks as free functions generic over C: ReactiveContext and return your own struct so callers get a typed handle:

src/lib.rs
use quoin_core::prelude::*;
use std::rc::Rc;
pub struct SearchBox<S: Signal<String>> {
pub query: S,
pub clear: Rc<dyn Fn()>,
}
pub fn use_search<C: ReactiveContext>(cx: &C) -> SearchBox<C::Signal<String>> {
let query = cx.create_signal(String::new());
let clear = {
let query = query.clone();
Rc::new(move || query.set(String::new()))
};
SearchBox { query, clear }
}

Import with use quoin_core::prelude::*; (framework-free crates) or use quoin::prelude::*; (application crates). The prelude includes the extension traits, so .map(), set_eq(), and create_resource() are available without extra imports.

Never store what you can compute. Derived signals recompute on read and work on every adapter:

let count = cx.create_signal(2u32);
// Free function form:
let label = quoin_core::derived(&count, |n| format!("count = {n}"));
assert_eq!(label.get(), "count = 2");
// Method form (from SignalExt):
let doubled = count.map(|n| n * 2);
// Combine two signals into a tuple:
let both = quoin_core::zip(&a, &b);

Keep derive closures cheap — they run on every read. When the computation is expensive, wrap it in a Memo, which caches its output until the source value changes.

The effect! macro runs a side effect whenever its dependencies change, with optional cleanup:

use quoin_macros::effect;
effect! {
deps: [query],
run: || {
let data = fetch_data(&query.get());
results.set(data);
},
cleanup: || {
cancel_pending_request();
}
}

Each adapter lowers this to its native mechanism: create_effect + on_cleanup on Leptos, use_effect + use_drop on Dioxus, and run-on-execute with cleanup-on-drop on GPUI. See the macros reference for the legacy watch: [...] syntax and full semantics.

When a handler writes several signals, wrap the writes in a batch so pull-based adapters (GPUI, Xilem) receive one re-render request instead of one per write:

cx.batch(|| {
a.set(1);
b.set(2);
});

Fine-grained frameworks batch internally, so the call is safe on every adapter.

Two rules keep a hook portable:

  1. Do not name adapter types. Use C::Signal<T> and trait methods; never GpuiSignal, LeptosSignal, or framework crates in hook signatures.
  2. Do not call framework APIs. Rendering, windowing, and event listener registration belong in the view layer (or in the declarative macros, which expand per framework).

If you need !Send futures such as DOM-touching work, use the executor’s spawn_local — see Loading Async Data.