re-frame.core¶
re-frame.core is the namespace application code calls. You use it to register event handlers, subscriptions, effects and views, to dispatch events and read subscriptions, and to boot the app and create frames.
A counter, from registration to mount:
(ns counter.core
(:require [re-frame.core :as rf]
[re-frame.adapter.reagent :as reagent-adapter]))
(rf/reg-event :counter/inc
(fn [{:keys [db]} _event]
{:db (update db :counter/value (fnil inc 0))}))
(rf/reg-sub :counter/value
(fn [db _query] (:counter/value db 0)))
;; reg-view binds `dispatch` and `subscribe` to the frame the view renders in.
(rf/reg-view counter []
[:button {:on-click #(dispatch [:counter/inc])}
"Clicked " @(subscribe [:counter/value]) " times"])
(defonce app-root (reagent-adapter/client-root))
(defn run []
(rf/init! reagent-adapter/adapter)
(reagent-adapter/render! app-root
[rf/frame-root {:id :rf/default} [counter]]
(js/document.getElementById "app")))
Optional features (machines, routing, flows, schemas, SSR, HTTP, resources) register through macros on this facade, listed under Feature registration, so one require covers every registration. Each feature's other functions and its keyword events and effects are documented on that feature's page. The Core guide teaches the model these functions implement.
Registration¶
The reg-* forms register a handler under an id (for reg-app-schema, a path).
Most take a metadata map before the handler. It is optional for reg-event, reg-sub, reg-fx, reg-cofx, reg-interceptor, reg-view*, reg-machine, reg-app-schema, reg-head and reg-error-projector, and required for reg-route, reg-flow, reg-resource, reg-mutation and reg-resource-scope. The others differ: reg-view takes a docstring and ^{:rf/id …} metadata on its symbol, reg-http-interceptor carries its metadata in its one interceptor map, and reg-app-schemas takes its options after the schema map.
On CLJS, the reg-* names are macros in call position and plain functions in value position, except reg-view and reg-machine, which are macros only; their function forms are reg-view* and re-frame.machines/reg-machine*. A call such as (rf/reg-event :counter/inc handler) records its source coordinates, so tools like Xray can go from a registration back to that expression. Passed as a value, as in (apply rf/reg-event args), the name is a function that skips the recording: the registration has no namespace, so an image's :select-ns cannot select it and only the default image runs it, unless its metadata carries :ns (see image). On the JVM the reg-* forms are macros only.
reg-event, reg-sub, reg-fx, reg-cofx and reg-interceptor accept these bare metadata keys:
| Kind | Bare metadata keys |
|---|---|
| all five | :doc, :schema, :tags |
reg-event |
adds :interceptors, :boundary?, :sensitive, :large, :large? |
reg-sub |
adds :inputs, :sensitive, :large, :large? |
reg-fx |
adds :platforms, :sensitive, :large, :large? |
reg-cofx |
adds :platforms, :recordable?, :provided?, :sensitive, :large, :large? |
reg-event, reg-sub and reg-interceptor also accept :platforms and store it, and nothing reads it. Namespaced keys (:rf.cofx/requires, :myapp/owner) are always accepted and stored. See What is validated for :schema, and Keep secrets out of traces for :sensitive and :large. Registering one of the five can raise these (see Errors):
:rf.error/retired-registration-key: the map carries re-frame v1's:spec; use:schema. Thrown in every build.:rf.error/bad-classification::sensitiveor:largeis not a vector of path vectors ([[]]for the whole value).:rf.warning/unknown-registration-key(development builds): a bare key outside the kind's set, usually a typo. The key is stored but never read.:rf.warning/missing-doc(development builds): a macro registration without:doc, once per id.:rf.warning/registration-collision(development builds): the id was already registered from a different source location. The new registration replaces the old one; re-evaluating the same file (hot reload) is silent.
reg-event¶
- Kind: macro
- Signature:
- Description: Registers an event handler; dispatching
[id …]runs it. The handler is(fn [coeffects event-vec] effect-map): it receives the coeffects map (:db,:event,:rf.frame/idand any coeffects it declares) and returns a closed effect map such as{:db … :fx […]}, ornilfor no effects.reg-eventis the only public event-registration form.- Return an effect map even when only
app-dbchanges. Returning the new db itself, or putting an fx id such as:dispatchbeside:db, rejects the event with:rf.error/effect-map-shape, and nothing commits (see The effect map). A non-map return emits:rf.error/effect-handler-bad-returnand the event does nothing. - A handler that throws emits
:rf.error/handler-exception, and the event commits nothing:app-dbis unchanged and no:fxrun. The rest of the queue still runs. - The optional metadata map carries reflection keys (
:doc,:schema,:tags, …) and the:interceptorsvector. Interceptors always go in the metadata map, never in a positional middle vector:(reg-event :id {:interceptors [:my/audit]} handler). - To read or rewrite the interceptor context, register a named interceptor with
reg-interceptorand reference it by id from:interceptors. Its:before/:afterfns receive and return the context map. There is no separate registration for raw-context handlers. {:boundary? true}makes this handler's own:schemarun in every build, including:advancedwithgoog.DEBUG=false, where development validation is otherwise removed. It adds no second schema. Set it on handlers that take data from outside the app: HTTP replies, websocket frames,postMessage.- The check runs before the interceptor chain, against the event vector as dispatched, so development and production validate the same value at the same point, and
:interceptor-overridescannot remove it. - A failed check skips the handler, sets
:outcome :rejected, and emits the always-on:rf.error/schema-validation-failurerecord with:source :boundary. See Validate with schemas.
- The check runs before the interceptor chain, against the event vector as dispatched, so development and production validate the same value at the same point, and
- See Handlers return descriptions.
- Return an effect map even when only
- Errors:
- At registration:
:rf.error/reg-event-db-removed,:rf.error/reg-event-fx-removed: calling re-frame v1'sreg-event-dborreg-event-fx; usereg-event.:rf.error/reg-event-ctx-removed: calling v1'sreg-event-ctx; register the context work withreg-interceptorand reference it from:interceptors.:rf.error/at-boundary-missing-schema:{:boundary? true}without a:schemakey. The key must be present:{:schema nil :boundary? true}registers.:rf.error/reg-event-bad-arity: neither(reg-event id handler)nor(reg-event id metadata handler).:rf.error/reg-event-bad-middle-slot: the middle argument is not a map, such as re-frame v1's positional interceptor vector.:rf.error/reg-event-bare-interceptor: an interceptor map passed as the middle argument instead of under:interceptors.:rf.error/reg-event-bad-interceptors::interceptorsis not a vector of interceptor ids (:my/icor[id arg]); an inline interceptor map in it raises:rf.error/inline-interceptor-removed.:rf.error/reserved-event-id: the id is one of the framework-owned events:rf/set-dband:rf/install-frame-state, or the retired:rf/settle-flows, which stays reserved.:rf.error/unregistered-interceptor: an:interceptorsentry names an id with noreg-interceptor. References are checked whenreg-eventruns, and a frame's:interceptorswhenmake-frameruns, so register interceptors first.:rf.error/interceptor-factory-arity: an entry's shape does not match the registered interceptor (seereg-interceptor). Factories do not run at registration, so[:rf.interceptor/path :cart]registers and throws:rf.error/path-interceptor-bad-pathwhen the event runs.:rf.error/cofx-request-invalid::rf.cofx/requiresis not a vector, or an entry is neither an id nor[id arg].:rf.error/cofx-name-collision::rf.cofx/requiresdeclares the same id twice.
- When the event runs:
:rf.error/effect-map-shape: the return breaks the effect map rules, for example the new db returned bare, which rejects the event.:rf.error/effect-handler-bad-return: the handler returned something other than a map ornil; the event does nothing.:rf.error/handler-exception: the handler threw; nothing commits.:rf.error/schema-validation-failurewith:source :boundary: under{:boundary? true}, the event vector failed the handler's:schema; the handler does not run.
- At registration:
- Example:
;; Don't do this: the new db is returned bare, so its keys sit at the top ;; level of the effect map and the event is rejected (:rf.error/effect-map-shape). (rf/reg-event :counter/inc (fn [{:keys [db]} _event] (update db :counter/value inc))) ;; State-only: the db write is an explicit :db effect. (rf/reg-event :counter/inc (fn [{:keys [db]} _event] {:db (update db :counter/value inc)})) ;; Effectful: an explicit :db write plus an :fx vector. (rf/reg-event :counter/load (fn [{:keys [db]} _event] {:db (assoc db :status :loading) :fx [[:rf.http/managed {:request {:method :get :url "/api/count"} :on-success [:counter/loaded] :on-failure [:counter/load-failed]}]]})) ;; Metadata: a doc string and an interceptor referenced by id. (rf/reg-event :cart/add {:doc "Add an item." :interceptors [:cart/undoable]} (fn [{:keys [db]} [_ item]] {:db (update db :items conj item)})) ;; Validate an untrusted payload in every build. (rf/reg-event ::receive-from-server {:schema [:cat [:= ::receive-from-server] PayloadSchema] :boundary? true} (fn [{:keys [db]} [_ payload]] {:db (assoc db :data payload)}))
reg-sub¶
- Kind: macro
- Signature:
-
Description: Registers a subscription: a value computed from
app-db, from other subscriptions, or both, which views read withsubscribe. Dependencies go under:inputsin the metadata map, in one of three forms:Mode Form Where the inputs come from App-db reader (reg-sub id computation-fn):inputsomitted. No upstream subscriptions; the computation fn receivesapp-dband the outerquery-v(layer 1).Static inputs (reg-sub id {:inputs [q1 q2]} computation-fn)A literal list of query vectors, known and shape-checked at registration. Parametric inputs (reg-sub id {:inputs producer-fn} computation-fn)Computed from the outer query-vwhen the subscription is first created for that query vector.- Use a subscription for a derived value that views read. When an event handler, a schema or another flow must read the derived value as plain
app-dbdata, keep it inapp-dbwith a flow (reg-flow) instead. - Declared inputs always arrive as a vector, in declaration order, whether there are zero, one or many. Moving a dependency between the literal and the fn form never changes the body, and adding a second input never turns a scalar argument into a vector.
{:inputs []}declares no dependencies and delivers[]; omitting:inputsdeliversapp-dbitself. - An
:inputsproducer fn is a pure function from the outerquery-vto a vector of query vectors. It must not callsubscribe, derefapp-db, dispatch, perform IO or return reactions. It never runs at registration; the runtime calls it when it creates the subscription for a query vector, and resolves each returned query vector in the same frame as the outer subscription. - There is no
reg-sub-raw;reg-subis the only subscription registration form. See When the inputs depend on the arguments for choosing between a literal vector and a fn. - Errors:
- At registration:
:rf.error/reg-sub-bad-args: the arguments are not(reg-sub id ?metadata computation-fn). This includes re-frame v1's:<-sugar, a leading input fn, and an:inputsthat isnil, not a vector of query vectors, and not a fn.
- When the subscription computes (the subscription yields
nil)::rf.error/sub-input-fn-bad-return: an:inputsfn returned something other than a vector of query vectors, such as[:a :b]for[[:a :b]].:rf.error/sub-input-fn-exception: an:inputsfn threw.:rf.error/sub-exception: the computation fn threw.:rf.error/sub-cycle(development builds): the subscription depends on itself through its inputs.
- Example:
;; Layer-1 — read straight off app-db (no :inputs, no producer) (rf/reg-sub :counter/value (fn [db _query] (:counter/value db))) ;; Layer-2 — declare the upstream sub; the body destructures the vector (rf/reg-sub :counter/doubled {:inputs [[:counter/value]]} (fn [[value] _query] (* 2 value))) ;; Parametric — the producer returns a vector of query vectors, computed ;; from the outer query-v; the runtime resolves each in the outer sub's ;; frame and hands the resolved values to the computation-fn. (rf/reg-sub :article/page {:inputs (fn [[_ article-id]] [[:article/by-id article-id] [:comments/for-article article-id] [:viewer/current]])} (fn computation-fn [[article comments viewer] [_ article-id]] {:id article-id :article article :comments comments :can-edit? (:edit? viewer)}))
- Use a subscription for a derived value that views read. When an event handler, a schema or another flow must read the derived value as plain
reg-fx¶
- Kind: macro
- Signature:
- Description: Registers an effect handler: the code that performs a side effect (network, storage, timers, the DOM), so that event handlers stay pure and only describe it. When an event handler returns
[id args]in its:fxvector, the runtime calls the handler afterapp-dbis committed. The handler takes the context first:(fn [ctx args] ...). A one-argument(fn [args] …)handler, the re-frame v1 shape, does not receiveargs: on CLJS it receivesctxin its place, and on the JVM the call fails with:rf.error/fx-handler-exception.ctxis a small map of:frame(the active frame id),:event(the originating event vector) and:envelope(the parent dispatch envelope).argsis the value the event handler placed beside the fx id in its:fxvector.- A handler that throws emits
:rf.error/fx-handler-exception: that effect is skipped, the other effects still run, and the:dbwrite stands. An:fxentry naming an unregistered id emits:rf.error/no-such-fxand is skipped the same way. - The
:platformsmetadata key (a set of:server/:client) runs the effect only on those platforms; it defaults to#{:client :server}. On a platform outside the set, the effect is skipped. See re-frame.ssr. - See The effect handler's two arguments.
- Errors:
- At registration:
:rf.error/fx-registration-invalid: no handler fn, as in the metadata-only(reg-fx :id {…}).
- When the effect runs:
:rf.error/fx-handler-exception: the handler threw; that effect is skipped, and the other effects still run.:rf.error/no-such-fx: an:fxentry names an unregistered id; that entry is skipped.
- At registration:
- Example:
reg-cofx¶
- Kind: macro
- Signature:
- Description: Registers a coeffect: a named fact about the world (the time, a stored preference, a browser setting) that an event handler can ask for instead of reading it itself, so the handler stays pure. The supplier is a plain function that returns the value synchronously,
(fn [] value), or(fn [arg] value)for an id parameterised at the call site. The runtime calls it and puts the result in the coeffects map under the cofx id.- A handler asks for coeffects with
:rf.cofx/requiresin its registration metadata:[:my/fact], or[[:my/fact arg]]for a parameterised id. The values arrive flat in the coeffects map, beside:db. There is norf/inject-cofxvar, so a leftover facade call fails to compile. The old implementation-namespacere-frame.cofx/inject-cofxstub throws:rf.error/inject-cofx-removed. - For the current time, declare the built-in
:rf/time-ms(epoch milliseconds, stamped when the event is queued). It needs no registration. -
The metadata map sets the fact's grade, which decides what happens on replay:
Grade Metadata Where the value comes from On replay Recordable neither key (the default) The supplier, or the dispatch's :rf.cofxopt; recorded with the event.The recorded value is presented. Provided {:provided? true}, no supplierThe event: stamped by the framework or a feature artefact, or passed in :rf.cofx.:rf/time-msis one.The recorded value is presented. Ambient {:recordable? false}The supplier, each time a declaring handler runs; not recorded. The supplier runs again and may answer differently. Use recordable for a world fact that ends up in
app-db, and ambient only for values noapp-dbwrite depends on, such as a display preference, or for a supplier that returns a host object. A handler that declares a provided fact the event does not carry fails with:rf.error/missing-required-cofx. - A recordable coeffect's value must be EDN (not a function, Promise or DOM node; ajs/Dateis a valid#inst), and must match the registration's:schemawhen the schemas artefact is loaded. Both are checked in every build as the value is recorded, and a failure throws:rf.error/cofx-value-invalid. See What is validated. - A handler that declares an unregistered id throws:rf.error/unregistered-cofxwhen its event runs; registration does not check it. A supplier that throws emits:rf.error/coeffect-exception, and the handler does not run. - Under the:strictmint policy, a recordable fact the dispatch did not supply is not generated, and the handler fails with:rf.error/missing-required-cofx. Frames made with:preset :testdefault to:strict, so tests pass the value in the:rf.cofxdispatch opt, or opt back into generation with{:rf.cofx/mint-policy :live}. -:platforms(a set of:client/:server) limits where the supplier runs. Elsewhere an ambient fact is absent from the coeffects map, and a recordable one fails with:rf.error/missing-required-cofx. - To read a subscription from a handler, wrapsubscribe-oncein a cofx and declare it. - See Coeffects. - Errors: - At registration: -:rf.error/cofx-registration-invalid::provided? truebeside:recordable? false, a supplier passed with:provided? true, or no supplier on a fact that is not provided. -:rf.error/cofx-name-collision: the id is:dbor:event, which are the handler's own arguments. - When a declaring event runs: -:rf.error/unregistered-cofx: the handler declares an id with noreg-cofx. -:rf.error/coeffect-exception: the supplier threw; the handler does not run. -:rf.error/missing-required-cofx: a declared fact has no value: a provided fact the event does not carry, a recordable fact the dispatch did not supply under the:strictmint policy, or a recordable fact on a platform outside its:platforms. -:rf.error/cofx-value-invalid: a recordable value is not EDN, or fails the registration's:schema. - Example:;; The built-in clock: declare it and read it flat. (rf/reg-event :todo/add {:rf.cofx/requires [:rf/time-ms]} (fn [{:keys [db rf/time-ms]} [_ text]] {:db (update db :todos conj {:text text :added-at time-ms})})) ;; An ambient supplier, parameterised by the storage key. The value only ;; styles the page and never reaches app-db, which is what makes ambient right. (rf/reg-cofx :ui/local-theme {:recordable? false :doc "Ambient localStorage read for the display theme."} (fn [storage-key] (some-> (.-localStorage js/globalThis) (.getItem storage-key)))) (rf/reg-fx :ui/set-theme-attr (fn [_ctx theme] (.setAttribute js/document.documentElement "data-theme" theme))) (rf/reg-event :prefs/apply-theme {:rf.cofx/requires [[:ui/local-theme "ui-theme"]]} (fn [{:keys [ui/local-theme]} _] {:fx [[:ui/set-theme-attr (or local-theme "system")]]}))
- A handler asks for coeffects with
reg-classification¶
- Kind: macro
- Signature:
- Description: Declares the app-db paths a feature makes sensitive or large, once, beside its other registrations, under the registrar kind
:classification.declis a closed map::sensitiveand:large, each a vector of paths absolute in app-db, plus an optional:doc. Every frame unions the declarations its own view resolves, so a declared path reads:rf/redacted(or the size marker) from its first egress, with no classification event, while handlers still see the real value. A retained epoch record keeps the declarations it was recorded under. Any other key, or a malformed path, throws:rf.error/bad-classification. See Spec 015 §Static app-db classification. - Example:
clear¶
- Kind: function
- Signature:
- Description: Removes one registration and returns its
id. It is the inverse of thereg-*forms, keyed by kind, for tests, REPL work and teardown. There are no per-kind names such asclear-eventorclear-resource.kindis one of:event,:sub,:fx,:cofx,:interceptor,:view,:route,:head,:error-projector,:app-schema,:classification,:flow,:resource,:mutation,:resource-scopeor:http-interceptor. A frame is not a registration; tear it down withdestroy-frame!.- Kinds that hold runtime state clean it up:
:flowemits:rf.flow/cleared, and each frame running the flow removes its output path on its next event;:routeemits:rf.route/cleared,:http-interceptoremits:rf.http.interceptor/cleared, and the resource kinds dispose per-frame runtime state. The other kinds only remove the registrar entry. - A registration belongs to no frame, so
clearremoves it for every frame at once and takes no opts. A trailing opts map throws:rf.error/registrar-clear-bad-request, as does an unknown kind, naming the valid kinds. To stop one frame running a flow or an HTTP interceptor, re-make that frame without it. - Clearing a kind whose optional artefact is not loaded throws that artefact's missing-artefact error, for example
:rf.error/flows-artefact-missingfor:flow. - There is no clear-all arity. Bulk clearing belongs to the test fixtures in
re-frame.test-support.
- Example:
Dispatch and subscribe¶
dispatch sends an event to a frame; subscribe reads a subscription.
On CLJS, dispatch and dispatch-sync are macros in call position and plain functions in value position, as most reg-* forms are (see Registration). A call such as (rf/dispatch [:counter/inc]) records its source coordinates, so tools like Xray can go from a trace event back to that expression. Passed as a value, as in (map rf/dispatch events) or (or dispatch-fn rf/dispatch), the name is a function that skips the recording. Both reach the same dispatcher, and there is no *-suffixed variant.
On the JVM the two are macros only. JVM code that needs a function calls re-frame.router/dispatch! or re-frame.router/dispatch-sync!.
subscribe is a plain function on both hosts, so (map rf/subscribe query-vs) works everywhere. It records no source coordinates of its own; inside a reg-view body the injected subscribe attributes a read's errors to the view.
A :frame that names no live frame (a typo, or a destroyed frame) does not throw: dispatch does nothing, subscribe returns nil, and the runtime emits :rf.error/frame-destroyed. With no :frame and no frame in scope, the call throws :rf.error/no-frame-context.
Dispatch options¶
dispatch and dispatch-sync take an optional opts map:
| Key | What it does |
|---|---|
:frame |
The frame to target: a frame-id keyword or a live frame value, as in (rf/dispatch [::save x] {:frame :todo}). |
:fx-overrides |
{fx-id override} for this dispatch; see with-fx-overrides for override values and precedence. |
:interceptor-overrides |
{interceptor-ref replacement} for this dispatch: replaces or removes interceptors in the chain. See Interceptor overrides. |
:rf.cofx |
Recordable coeffect values to supply, such as {:rf/time-ms 0}, for tests, replay and SSR hydration. The runtime adds :rf/time-ms when it is absent. A value that is not a map, or a non-integer :rf/time-ms, makes the call throw :rf.error/invalid-cofx; a value that is not plain EDN (a fn, Promise or DOM node) throws :rf.error/cofx-value-invalid. Both are checked in every build. |
:rf.cofx/mint-policy |
Whether a declared recordable coeffect the dispatch did not supply may be generated. :live runs its supplier; :strict fails the handler with :rf.error/missing-required-cofx, and any other value behaves as :strict. Unset, the frame's :rf.cofx/mint-policy applies (:strict under :preset :test), then :live. A test on a :strict frame opts back into generation with :live. See Coeffects. |
:source |
What triggered the dispatch, recorded on traces. Application code passes :ui, :repl, :tool, :test, :websocket or :other; unset, it is :unknown. The framework stamps the other values itself: :frame-init, :fx-dispatch, :fx-dispatch-later, :machine-spawn, :machine-action, :always, :after-timer, :http, :router, :ssr-hydration. |
:origin |
Who dispatched: an open keyword, :app by default. |
:trace-id |
A correlation id that tools attach to the dispatch's traces. |
An unrecognised key does nothing, and development builds emit :rf.warning/unknown-dispatch-opt. subscribe and subscribe-once read only :frame.
Events a handler queues with [:dispatch …] or [:dispatch-later …] inherit :frame, :fx-overrides, :interceptor-overrides, :rf.cofx/mint-policy, :origin and :trace-id from the dispatch that ran it. Each queued event gets its own :rf.cofx and :rf/time-ms, and its :source is :fx-dispatch or :fx-dispatch-later.
Interceptor overrides¶
:interceptor-overrides replaces or removes interceptors in an event's chain without re-registering the event, usually to stub or drop an interceptor such as logging or analytics in a test. It is a dispatch option, applying to that dispatch and the events it queues, and a frame config key, applying to every event in the frame.
The value is a map {interceptor-ref replacement}:
- A key is an interceptor reference: a keyword id, or an
[id arg]2-vector. A keyword key matches every reference to that id,:my/icand[:my/ic arg]alike, because it matches the resolved interceptor's:id. An[id arg]key matches only that exact reference, so{[:rf.interceptor/path [:cart]] nil}removes that one and leaves[:rf.interceptor/path [:cart :items]]in the chain. - A replacement is
nil, which removes the interceptor, or an interceptor reference, resolved through the registrar like any chain entry; an unregistered id throws:rf.error/unregistered-interceptor. - A malformed key, or a replacement that is neither
nilnor a reference (such as an inline interceptor map), throws:rf.error/interceptor-override-invalid, with:keyand:replacementin its ex-data and the recovery:fix-overrides. Keys are checked on every dispatch that has overrides; a replacement is resolved only when its key matches an entry in the chain. - The frame's
:interceptor-overridesand the dispatch's merge, and the dispatch's wins on a shared key. The frame's:interceptorsare prepended before overrides apply, so an override reaches them too. - Events queued with
[:dispatch …]or[:dispatch-later …]inherit the dispatch's map. - The
{:boundary? true}schema check ofreg-eventruns before the chain, so no override can remove it. - In development builds the run's
:rf.event/run-starttrace event carries:rf.interceptor/override-summary:{:matched […] :replaced […] :removed […] :count n}, naming the keys that matched an entry. A key that matched nothing is not listed. - An epoch record carries the dispatch's map as
:interceptor-overrides, never the frame's, soreplay-epoch!supplies the recorded map and the frame's own config applies as it stands at replay.
(rf/reg-interceptor :app/audit
{:after (fn [ctx] (send-audit! (get-in ctx [:coeffects :event])) ctx)})
(rf/reg-interceptor :test/audit-stub {:after identity})
(rf/reg-event :cart/add
{:interceptors [:app/audit]}
(fn [{:keys [db]} [_ item]] {:db (update db :items (fnil conj []) item)}))
;; In a test: swap the audit interceptor for a stub, or drop it.
(rf/dispatch-sync [:cart/add :apple] {:interceptor-overrides {:app/audit :test/audit-stub}})
(rf/dispatch-sync [:cart/add :pear] {:interceptor-overrides {:app/audit nil}})
;; Don't do this: a replacement is a registered id or nil, never an inline
;; interceptor map. This throws :rf.error/interceptor-override-invalid.
(rf/dispatch-sync [:cart/add :fig] {:interceptor-overrides {:app/audit {:after identity}}})
dispatch¶
- Kind: macro
- Signature:
- Description: Queues the event on the frame and returns
nilimmediately; the handler runs later. This is the default way to send an event.optsis the map described under Dispatch options.rf/dispatchfinds its frame when it is called: during a view's render, inside an event handler (child dispatches go to the handler's frame), or insidewith-frame. A callback that fires later, such as an:on-click, a timeout or a promise, runs after that scope has gone, sorf/dispatchthere throws:rf.error/no-frame-context.- Inside a
reg-viewbody, use the injecteddispatch: it is bound to the view's frame when the view renders, so it still targets that frame from any callback. Elsewhere, capture the frame withcapture-frame, or pass{:frame …}. See The async boundary: capture the frame. - An event id with no registered handler emits
:rf.error/no-such-handler, and the event does nothing. - One family runs at most 1000 events (the frame's
:drain-depth; 16 under:preset :story). A family is one external event, or onedispatch-syncseed, plus every event dispatched while it runs, transitively; the count restarts at each external event, so events queued from outside never add up against it. If a family reaches the limit with its own events still queued, those are dropped, the events that ran stay committed, the always-on:rf.error/drain-depth-exceededlists the last event ids it ran (:tail-event-ids), which usually show the dispatch loop, and the drain carries on with the next external event. See When the drain won't stop. - Development builds emit
:rf.warning/non-serialisable-event-payloadwhen the event holds a fn, Promise, AbortController, DOM node or RegExp. An instant (js/Date) is EDN and draws no warning. The event still runs, but replay and SSR hydration expect plain data.
- Example:
;; Don't do this: when the click fires there is no frame in scope, ;; so rf/dispatch throws :rf.error/no-frame-context. (rf/reg-view counter-button [] [:button {:on-click #(rf/dispatch [:counter/inc])} "+"]) ;; The injected `dispatch` was bound to the view's frame at render. (rf/reg-view counter-button [] [:button {:on-click #(dispatch [:counter/inc])} "+"])
dispatch-sync¶
- Kind: macro
- Signature:
- Description: Processes the event and drains the queue to completion, then returns
nil. Use it in tests, at the REPL and for one-shot boot events, where the next line needs the new state; views and handlers usedispatch. See Run to completion.optsis the map described under Dispatch options.- Handler, interceptor, coeffect-supplier and effect failures are reported under their error ids, not thrown. Problems found while preparing the event do throw: no frame in scope, an invalid
:rf.cofx, an unregistered or missing declared coeffect. - A call that targets a frame while that frame is processing events (from one of its handlers, interceptors or effect handlers) is rejected: the event does not run, and development builds emit
:rf.error/dispatch-sync-in-handler. Return a[:dispatch …]effect instead. - A call that targets a different frame from inside a drain runs, and development builds emit
:rf.warning/cross-frame-dispatch-sync-during-drain.
- Example:
;; A one-shot boot event: app-db is initialised before the next line runs. (rf/make-frame {:id :rf/default}) (rf/dispatch-sync [:counter/initialise] {:frame :rf/default}) ;; Drive a sequence of events synchronously from a test or script. (doseq [evec events] (rf/dispatch-sync evec {:frame :rf/default}))
subscribe¶
- Kind: function
- Signature:
- Description: Returns a reaction whose value is the subscription's current output, recomputed when its inputs change; deref it to read. Use it in a view's render body, where the deref also re-renders the view when the value changes. An event handler reads a subscription through a coeffect (see
reg-cofx); a one-off read outside a view usessubscribe-once.- It finds its frame the way
dispatchdoes, so call it while the view renders, not from a callback that runs later. Inside areg-viewbody, the injectedsubscribeis bound to the view's frame. (rf/subscribe [:counter/value] {:frame :other})targets another frame;:othermay be a frame-id keyword or a live frame value.- A query id with no registered subscription emits
:rf.error/no-such-sub, and the reaction derefs tonil. The miss is not cached, so a later registration takes effect on the nextsubscribe.
- It finds its frame the way
- Example:
subscribe-once¶
- Kind: function
- Signature:
- Description: Reads a subscription's current value once: subscribes, derefs and unsubscribes, keeping no reactive handle. Use it at the REPL, in tests, in SSR code and in tools. Not in views, which need
subscribeto re-render.- An event handler that needs a derived value should declare a cofx that calls
subscribe-once(seereg-cofx) rather than call it in the handler body. If handlers need the value routinely, a flow is the better fit. - Machine
:guard,:action,:entryand:exitfns must not call it. A machine takes host facts as recorded coeffects, including the machines-only{:rf/sub …}source (see re-frame.machines). (subscribe-once query-v {:frame f})targets another frame, as forsubscribe. With no:frameand no frame in scope, it throws:rf.error/no-frame-context.
- An event handler that needs a derived value should declare a cofx that calls
- Example:
unsubscribe¶
- Kind: function
- Signature:
- Description: Hands back one share of
r, the reactionsubscribereturned. When the last share goes, the cache entry is disposed synchronously (see Subscriptions). The Reagent and UIx adapters release their own reads on unmount, so most code never calls it.- The release is identity-guarded: a reaction whose cache slot has since been evicted (a hot reload,
clear-sub-cache!, its frame destroyed) is a no-op, so a late release never disposes another holder's entry.nilis a no-op too. - It takes no frame and no query. A query vector throws
:rf.error/bad-unsubscribe-arg.
- The release is identity-guarded: a reaction whose cache slot has since been evicted (a hot reload,
- Example:
clear-sub-cache!¶
- Kind: function
- Signature:
- Description: Disposes every entry in a frame's subscription cache, synchronously and unconditionally. The no-argument form uses the current frame and raises
:rf.error/no-frame-contextoutside a frame scope; the one-argument form names the frame. Mostly for tests. - Example:
compute-sub¶
- Kind: function
- Signature:
- Description: Computes a subscription against a db value and returns the result, with no cache, no reactivity and no frame. The query vector comes first, the db second.
- An event handler reads framework state with it: it computes the vector a view subscribes to against the
runtime-dbit receives as:rf.db/runtime, such as(rf/compute-sub [:rf/machine id] rt)or(:nav-token (rf/compute-sub [:rf/route] rt)), rather than spelling where the framework stores that state. - A test uses it to check what a subscription computes (Test a subscription).
dbis a plainapp-dbmap, aruntime-dbmap for a framework subscription such as[:rf/machine id]or[:rf/route], or a full frame-state value ({:rf.db/app … :rf.db/runtime …}) when the graph mixesapp-dbandruntime-dbsubscriptions.- Runs on the JVM.
- An unregistered query id computes to
nil, and an unregistered input deliversnilto the computation fn, both with no error, so check the ids when a test reads an unexpectednil. - A computation fn that throws emits
:rf.error/sub-exceptionand computesnil. A subscription that depends on itself emits:rf.error/sub-cycle, and the cyclic input deliversnilto the computation fn.
- An event handler reads framework state with it: it computes the vector a view subscribes to against the
- Example:
;; Evaluate :counter/doubled against a literal app-db value (no frame, no cache). (rf/compute-sub [:counter/doubled] {:counter/value 21}) ;; => 42 ;; In an event handler, read a machine's state from the runtime-db it receives. (rf/reg-event :editor/save (fn [{:keys [db] rt :rf.db/runtime} _] (when (= :editing (:state (rf/compute-sub [:rf/machine :editor/flow] rt))) {:db (assoc db :editor/saving? true)})))
Standard events¶
The framework registers a few :rf/* events that you dispatch like any other. Registering :rf/set-db or :rf/install-frame-state yourself with reg-event throws :rf.error/reserved-event-id. Keep your own ids out of the :rf/* namespace.
:rf/set-db¶
- Kind: event
- Payload:
- Description: Replaces the whole
app-dbwith the given map; it does not merge. Use it to seedapp-dbwhen a frame is created, or to reset it. It goes through the normal event pipeline (schema validation, rollback, trace emission, epoch recording) like any other event. Its handler returns{:db new-db}, so it changesapp-dbonly, neverruntime-db.- It takes exactly one map. A missing,
nilor non-map argument, or any extra argument ([:rf/set-db {} :junk]), fails the handler with:rf.error/set-db-bad-value. A dispatch reports it as:rf.error/handler-exceptionand leavesapp-dbunchanged; as an:initial-eventsstep it aborts frame creation with:rf.error/initial-events-step-failed.[:rf/set-db {}]emptiesapp-db.
- It takes exactly one map. A missing,
- Example:
:rf/install-frame-state¶
- Kind: event
- Payload:
- Description: Installs saved frame state, for app-authored persistence.
frame-state-valuereads the state to save. A present:rf.db/appreplacesapp-db; a present:rf.db/runtimereplaces eachruntime-dbsubtree it carries and keeps the rest; an absent partition is left alone.- When the payload carries
:rf.runtime/machinesand the machines artefact is loaded, the restored machines':aftertimers are re-armed after the commit. - The whole payload is classified
:sensitive, so traces and egress records show:rf/redactedin its place. - A non-map payload, a present non-map partition, or a resource runtime subtree (
:rf.runtime/resources,:rf.runtime/mutations) throws; the router reports it as:rf.error/handler-exceptionand nothing is installed.
- When the payload carries
- Example:
Views¶
Register views with reg-view. Give a subtree its frame with frame-root when the subtree should bring the frame into being, or frame-provider when the frame already exists; Frames covers when you need more than one.
Frames, subscriptions, dispatch, source metadata and registry ids work the same under every adapter, and capture-frame works under all of them. Adapter-specific functions are on each adapter's page: re-frame.adapter.reagent and re-frame.adapter.uix, whose components read and dispatch through the use-sub and use-frame hooks.
reg-view¶
- Kind: macro
- Signature:
- Description: Defines and registers a view with a
defn-like form. This is the form application code uses, for any component that subscribes or dispatches.- It
defs the symbol, so sibling code renders the view as[my-view item]. - The id is the current namespace plus the symbol (
my.app.views/counter-buttonsregisters:my.app.views/counter-buttons), unless^{:rf/id …}metadata names one. dispatchandsubscribeare bound inside the body to the frame the view renders in. They are bound at render, so they keep that frame in callbacks such as:on-click, whererf/dispatchhas none (seedispatch).- The injected
dispatchtakes[event]or[event opts], always targets that frame (a:frameinoptsis ignored), and records:source :ui. - The injected
subscribetakes only the query vector. To read another frame, callrf/subscribewith{:frame …}during render.
- The injected
- A docstring becomes the view's
:doc. - A body that is not
defn-shaped throws:rf.error/reg-view-bad-argsat macroexpansion. - Render a view by Var reference or with
(rf/view id). A keyword head such as[:my-view "args"]is an HTML element, never a registered view. - See What
reg-viewadds.
- It
- Example:
reg-view*¶
- Kind: function
- Signature:
-
Description: Registers a view from a plain function, with no
def, no injecteddispatch/subscribeand no compile-time shape check. Use it when:- the id is computed (code generation, plugin systems, story scaffolding);
- you don't want a Var (inside a
letor a closure); - you are writing a Form-3 component,
(rf/reg-view* :id (r/create-class {...})), the one reason application code reaches for it; - you are writing library code that registers views without imposing a
def.
For frame-bound dispatch in a
reg-view*body, call(rf/capture-frame)at render and use its ops. - Example:;; Computed id — the id isn't a literal symbol at the call site. (defn register-panel! [view-id render-fn] (rf/reg-view* view-id render-fn)) ;; Form-3 — create-class isn't defn-shaped, so it registers through the ;; starred form. Capture the frame at render so lifecycle callbacks dispatch ;; to the captured frame. (rf/reg-view* :editor/page (fn [_] (let [{:keys [dispatch]} (rf/capture-frame)] (r/create-class {:component-did-mount (fn [_] (dispatch [:editor/mounted])) :reagent-render (fn [] [editor-form-view])}))))
view¶
- Kind: function
- Signature:
- Description: Looks up a registered view by id and returns what renders it, or
nilwhen the id is not registered. On CLJS that is the installed adapter's component head for the view, rendered as[(rf/view :id) args...]under Reagent and($ (rf/view :id) props)under UIx; on the JVM it is the registered render fn. It does not return hiccup. Use it as[(rf/view :id) args...]when you hold an id rather than the symbol: a stored view id, plugin-style dispatch, dynamic chrome. Otherwise render by Var reference ([my-view args]).- Under UIx, register a
defuicomponent withreg-view*and mount the head with$; see Registry-keyed views for how the head passes props and children.
- Under UIx, register a
- Example:
frame-provider¶
- Kind: component (Reagent)
- Signature:
- Description: Scopes a subtree to a frame that already exists; it creates, refreshes and destroys nothing.
dispatchandsubscribeinside the subtree target that frame. To create the frame if it is absent, useframe-root. It is the React counterpart ofwith-frame. See frame-provider and frame-root.:frameis a frame-id keyword or a live frame value. An absent frame raises:rf.error/frame-provider-frame-absent, anil:frameraises:rf.error/no-frame-context, and any other value raises:rf.error/bad-frame-provider-arg.- Passing
:id(theframe-rootkey) raises:rf.error/frame-provider-given-id, namingframe-root.
- Example:
frame-root¶
- Kind: component (Reagent)
- Signature:
- Description: Creates the named frame if it is absent, or reuses it without re-seeding if it is live, and provides it to the subtree. It takes
make-frame's options; see Frame config keys.:idis required and must be a keyword; otherwise it raises:rf.error/frame-root-missing-id.- The frame is created at commit, in a client
useLayoutEffect, not during render. The first render emits no children; once the frame exists, the children render against it. A render React discards before commit (a Suspense abort, a discarded concurrent render) creates and seeds nothing. - A remount reuses the frame without re-seeding it. Hot reload, StrictMode's development double-invoke, Story re-evaluation and a keyed remount all keep durable state;
:initial-eventsrun once, when the frame is first created. - Unmounting does not destroy the frame. To own a frame's lifetime explicitly, call
make-frameanddestroy-frame!yourself, for example in acreate-class. - Changing
:idor other options on a mountedframe-rootraises:rf.error/frame-root-reconfigured; to switch frames, give theframe-roota Reactkeythat changes. Passing:frame(theframe-providerkey) raises:rf.error/frame-root-given-frame, namingframe-provider. - See frame-provider and frame-root.
- The frame is created at commit, in a client
- Example:
capture-frame¶
- Kind: function
- Signature:
- Description: Captures a frame and returns a bundle of operations bound to it. Use it for code that runs after the view body or handler has returned (
Promise.then,setTimeout, WebSocketonmessage, observer callbacks), where the frame is no longer in scope.- A
reg-viewbody rarely needs it: the injecteddispatchandsubscribeare already capture-frame operations. Reach for it inreg-view*bodies, effect handlers and other code that hands a callback to a JavaScript API. (capture-frame)captures the current frame at the moment of the call and raises:rf.error/no-frame-contextoutside a frame scope.(capture-frame frame-id)binds the bundle to a named frame and works anywhere.:dispatchand:dispatch-synctake[event]or[event opts];:subscribetakes only[query-v]. They always target the captured frame, and a:frameinoptsis ignored.- The bundle is bound to the frame instance that was live when it was captured. Once that frame is destroyed, even if a new frame is later made under the same id, the dispatch ops do nothing and
:subscribereturnsnil, each emitting:rf.error/frame-destroyed.(capture-frame frame-id)for an id with no live frame follows whichever frame holds the id when an op runs. - The bundle holds operations, not state. Read the frame's
app-dbwith(rf/app-db-value (:frame handle)). - See Frames for the async-boundary rules.
- A
- Example:
;; An effect that opens a socket: each message arrives long after the ;; handler returned, so capture the frame the effect ran for. (rf/reg-fx :chat/connect (fn [{:keys [frame]} url] (let [{:keys [dispatch]} (rf/capture-frame frame) socket (js/WebSocket. url)] (set! (.-onmessage socket) (fn [e] (dispatch [:chat/received (.-data e)]))))))
with-frame¶
- Kind: macro
- Signature:
- Description: Makes an existing frame the current frame for the dynamic extent of
body, in code that is not a view tree: tests, the REPL, SSR. It is the block-scoped counterpart offrame-provider.frameis a frame-id keyword or a live frame value.- It creates and destroys nothing.
- For a callback that runs after
bodyreturns, usecapture-frame. - It does not check that the frame exists: calls inside
bodyfollow the missing-frame rule under Dispatch and subscribe. - Passing
with-new-frame's binding vector throws:rf.error/with-frame-vector-format macroexpansion. - See Scoping a frame in a test or at the REPL.
- Example:
with-new-frame¶
- Kind: macro
- Signature:
- Description: Evaluates
expr(usually amake-framecall), binds the resulting frame tosym, runsbodywith it as the current frame, and destroys the frame on exit, whetherbodyreturns or throws. Use it for throwaway frames in tests and one-off harnesses. It returns the value ofbody. Passing a keyword, thewith-frameshape, throws:rf.error/with-new-frame-keyword-form, and any other binding that is not[sym expr]throws:rf.error/with-new-frame-bad-binding, both at macroexpansion. See Scoping a frame in a test or at the REPL. - Example:
reg-state¶
- Kind: macro
- Signature:
- Description: Registers per-instance view state for
concern: one subscription and one setter event, both underconcern, stored inapp-dbat[:ui concern instance-key], plus the shared:rf.state/clearevent that returns an instance to its default. It works the same under every view substrate. Use it for a value that means nothing beyond itself, such as a disclosure's open flag or a tab strip's selection; when a change must trigger something else or be recorded, write a named event instead.- Read with
[concern instance-key], write with[concern instance-key value], and clear with[:rf.state/clear concern instance-key]. An absent entry reads as:default. concernmust be a namespace-qualified keyword, since it is a subscription id, an event id and anapp-dbkey at once.optstakes only:default.- The instance key is a keyword, string, number, UUID, or a vector of those; derive it from data, the way you would a React
:key.nilis refused, because it is what a missing prop evaluates to and would make every instance share one value. - Registering the same concern again replaces all three registrations, so the last
:defaultwins. - See A widget's own state, and for Fresco views Application-visible state.
- Read with
- Errors:
:rf.error/state-bad-argument, thrown byreg-state, for an unqualified concern, or options that are not a map or carry a key other than:default. The message names the fault.- A bad instance key raises the same id inside the subscription or event, where the runtime catches it: a read emits
:rf.error/sub-exceptionand readsnil, and a write or clear emits:rf.error/handler-exceptionand changes nothing.
- Example:
Effects and interceptors¶
An event handler returns an effect map describing what should happen; the runtime applies it after the handler returns, so the handler stays pure. The interceptor chain runs before and after the handler.
The effect map¶
The effect map is closed. It has three top-level keys:
| Key | Value | Rules |
|---|---|---|
:db |
The new app-db, installed at commit. |
{:db nil} installs {}, and development builds emit :rf.warning/db-nil-coerced, since a nil is usually a bug; return {:db {}} to clear app-db on purpose. |
:fx |
A vector of [fx-id args] entries ([fx-id] with no args), each run by the handler registered with reg-fx. |
Must be a vector or nil; any other value, such as a bare map, rejects the event with :rf.error/effect-map-shape. nil and [] entries are skipped, so (when saving? [:app/save doc]) works as a conditional effect. An entry that is not a vector, has a non-keyword fx id or has more than two elements emits :rf.error/effect-map-shape and is dropped; the other entries run and the :db write stands. |
:rf.db/runtime |
Reserved for the framework and runtime extensions. | An application handler that returns it still has it applied, and development builds emit :rf.warning/app-handler-runtime-effect. |
Any other top-level key rejects the event before anything commits, so a valid :db beside it does not land either, and the runtime emits :rf.error/effect-map-shape. Classification is not an effect: a :sensitive or :large key here is rejected the same way, with a :reason naming reg-classification, which is where app-db paths are classified. These checks apply to the final effect map, including keys an interceptor's :after adds. See The effect map.
reg-interceptor¶
- Kind: macro
- Signature:
- Description: Registers a named interceptor, which event handlers and frames then reference by id in their
:interceptorsvector. Use it for work that wraps many handlers, such as logging, analytics or validation, and for any handler that must read or rewrite the interceptor context.descriptoris{:before f},{:after f},{:before f :after g}, or{:factory f}for a parameterized family. A malformed descriptor raises:rf.error/invalid-interceptor.- A factory's
ftakes one argument and returns a descriptor, and a chain references it as[id arg]. The standard[:rf.interceptor/path …]is a factory. A factory referenced as a bare keyword, a static interceptor referenced as[id arg], or a factory that throws or returns no descriptor raises:rf.error/interceptor-factory-arity. - Each
:beforeand:afterfn receives and returns the interceptor context. The context has:coeffects(:db,:event,:rf.frame/idand the declared coeffects) and:effects(the handler's effect map).:beforefns run in chain order before the handler, and:afterfns in reverse order after it. A fn that returnsnilleaves the context unchanged. - A fn that throws emits
:rf.error/interceptor-exception, naming the interceptor and its:phase. Later:beforefns and the handler are skipped, every:afterstill runs, and the event commits nothing. - The optional middle slot is the standard registration-metadata map (
:doc,:schema,:tags, …). - A chain carries ids only. An inline interceptor map in an
:interceptorsvector raises:rf.error/inline-interceptor-removed, and an id that is not registered raises:rf.error/unregistered-interceptor. - On CLJS the name is also a plain function in value position, as for
dispatch; JVM code that needs a function callsre-frame.interceptor-registry/reg-interceptor*. There is no public constructor for interceptor values. - See Interceptors.
- Errors:
- At registration:
:rf.error/invalid-interceptor: the descriptor is malformed.
- When a
reg-eventregisters a chain that references it::rf.error/unregistered-interceptor: the chain names an id with noreg-interceptor.:rf.error/interceptor-factory-arity: a factory referenced as a bare keyword, a static interceptor referenced as[id arg], or a factory that throws or returns no descriptor.:rf.error/inline-interceptor-removed: the chain holds an inline interceptor map instead of an id.
- When the event runs:
:rf.error/interceptor-exception: a:beforeor:afterfn threw; the event commits nothing.
- At registration:
- Example:
Standard effects and interceptor¶
The framework reserves a few :fx ids and one standard interceptor reference; register your own fx ids with reg-fx. Feature fx ([:rf.http/managed …], [:rf.nav/push-url …], [:rf.machine/spawn …], [:rf.server/* …], …) are documented on each feature's page.
[:dispatch event-vec]¶
- Kind: effect (reserved fx-id)
- Payload:
[:dispatch event-vec] - Description: Queues
event-vecon the same frame's queue. It runs after the current pipeline run completes. This is how a handler triggers another event; it cannot calldispatch-sync.- The queued event inherits opts from the event that queued it; see Dispatch options.
- Example:
[:dispatch-later {…}]¶
- Kind: effect (reserved fx-id)
- Payload:
[:dispatch-later {:ms ms :event event-vec}], optionally with:id id; or[:dispatch-later {:id id :cancel? true}] - Description: Queues
event-vecon the same frame aftermsmilliseconds. Use it instead of asetTimeoutin a handler, which would have no frame when it fires.:msis the delay in milliseconds. A missing or non-numeric:msis refused: nothing is queued, the always-on:rf.error/fx-handler-exceptionis emitted carrying the offending:ms, and the rest of the:fxvector still runs.:id, any value, names the timer within the frame. Arming an:idthat is still pending cancels the pending timer first, so the later arm replaces it: that is debounce.{:id id :cancel? true}cancels the pending timer and arms nothing; a cancel with no:idis refused like a bad:ms. Each replace or cancel of a pending timer emits a:rf.fx/dispatch-later-cancelledtrace.- A pending timer is cancelled when its frame is destroyed, so the event never runs.
- The queued event inherits opts from the event that queued it; see Dispatch options.
- Example:
[:rf.interceptor/path path-vector]¶
- Kind: interceptor reference
- Payload:
[:rf.interceptor/path path-vector], inside an:interceptorsvector - Description: Focuses a handler on one slice of
app-db::beforeputs(get-in db path)in the coeffects as:db, the handler returns a new slice, and:afterwrites it back into the fullapp-db. It is the only standard interceptor.- If the handler returns the slice unchanged,
:afterreturns the originalapp-dbobject instead of a freshassoc-in, so the commit sees no change. - A path that is not a vector raises
:rf.error/path-interceptor-bad-pathwhen the event registers. - It is referenced by id; there is no
pathfunction, and callingrf/pathraises:rf.error/path-removed. - See The one standard interceptor:
path.
- If the handler returns the slice unchanged,
- Example:
Frames¶
A frame holds one running instance of your app: its app-db, event queue and subscription cache. Registrations are shared: unless a frame is built from images, every frame runs the same handlers against its own state. Most apps have one frame, created at the root with rf/frame-root. init! does not create one, and an operation outside any frame scope throws :rf.error/no-frame-context rather than falling back to a default frame (see Frame identity is carried, not found).
Create more frames when the same app must run more than once side by side, each copy isolated: the same widget twice on a page, Story canvases, a fresh frame per test, a frame per SSR request. Two parts of one app that ever share state belong in one frame: frames do not split an app into subsystems, and a subscription never reads another frame. Target a frame from outside its scope with {:frame :other}.
Which function makes the frame depends on who owns its lifetime:
- A view subtree that should bring its frame into being:
frame-root. It creates the frame on first mount and keeps it on unmount. - A subtree rendering a frame that already exists:
frame-provider. - Code that creates and tears down the frame itself (tests, SSR requests, a modal discarded on close):
make-framewithdestroy-frame!, orwith-new-framefor a body of code. - Code outside a view tree that runs against an existing frame (tests, the REPL, SSR):
with-frame.
make-frame¶
- Kind: function
- Signature:
- Description: Creates a frame and returns the live frame value. Use it when your code owns the frame's lifetime: devcards, modal stacks, several live instances of a widget, dynamic tabs, tests, and one frame per SSR request. For a frame tied to a view subtree, use
frame-root. There is noreg-frame: a frame is a live runtime object, not a registration.optsmust be a map. Every key is optional; the keys are listed under Frame config keys.- Creating a frame under an id that is already live replaces it idempotently, keeping durable state across a re-mount:
app-db,runtime-db, the queue and the subscription cache survive. The new config replaces the old one whole, so a key you leave out is dropped rather than kept from the earlier call, and a new:initial-eventsis recorded but not run. - The two-argument form resolves
:imagesagainst an explicit descriptor pool, for tests and harnesses. - Pass the returned value wherever a frame is expected.
dispatch,subscribe,app-db-valueandframe-provideraccept the value or its id and treat them the same, so there is no value-to-id accessor.destroy-frame!accepts both too, but treats them differently; seedestroy-frame!. - Pair each
make-framewith adestroy-frame!, or useframe-rootfor frames tied to a view. See Frames.
- Errors: each one throws, and no frame is left behind. See Assembly errors for the
image-*errors.:rf.error/make-frame-bad-opts:optsis not a map, includingnil.:rf.error/make-frame-bad-images::imagesis not a vector, or is[].:rf.error/unknown-preset::presetis not:default,:testor:story.:rf.error/image-duplicate-id: two namespaces register the same[kind id]in one image's selection, including the default projection of an explicit descriptor pool. Rename one, narrow:select-ns, or put the intended override in a later image. A frame made without:imagesover the registrar is still made, and using that id raises:rf.error/ambiguous-registrationinstead.:rf.error/image-zero-match: an image's:select-ns :includepattern matches no loaded registration (a typo, or a namespace not required).:rf.error/image-duplicate-image-id: images in a multi-image:imagesvector share an:id, or one has no:id.:rf.error/image-within-image-collision: an inline registration collides with a selected one in the same image.:rf.error/image-standard-replacement-forbidden: an app registration collides with a protected framework standard such as:rf/set-db.:rf.error/image-missing-reference: an event names an interceptor, or a resource names a scope resolver, that the image does not provide.:rf.error/unregistered-interceptor: an entry in the frame's own:interceptorsnames an id the frame's image does not register. The chain is resolved when the frame is made, so a typo fails here rather than at the first dispatch.:rf.error/frame-construction-in-handler: a new frame was created inside an event handler. Create frames at top level or withframe-root.:rf.error/frame-construction-in-progress: the id's construction or destruction is still under way (re-entry from its own setup, or another JVM thread). Retry once it settles.:rf.error/bad-frame-classification: a:sensitiveor:largekey, or a malformed:observabilityentry.:rf.error/routing-artefact-missing::url-strategywithoutre-frame.routingloaded.:url-bound?alone is accepted before routing loads.:rf.error/resources-artefact-missing::revalidate-onwithoutre-frame.resourcesloaded.:rf.error/http-bad-interceptor::http-interceptorsis not a vector of keyword ids.:rf.error/initial-events-bare-event::initial-eventsis one bare event vector ([:app/boot]) instead of a vector of steps.:rf.error/initial-events-bad-step,:rf.error/initial-events-bad-event,:rf.error/initial-events-bad-opts: a malformed step.:rf.error/initial-events-step-failed: a step's handler, an interceptor, a coeffect or a flow threw. The frame is destroyed, and the error names:step-indexand:event.
- Example:
Frame config keys¶
The keys of the map make-frame and frame-root take. Every key is optional, except that frame-root requires :id.
| Key | Value | Default | Meaning |
|---|---|---|---|
:id |
A keyword. | A generated :rf.frame/<n> id. |
The frame's id. A frame made without one is listed by frame-ids under its generated id; address it through the value make-frame returns. |
:images |
A non-empty vector of images. | The default image. | The registrations the frame runs. The default image runs every registration, looked up live as each event begins, and an id two namespaces register raises :rf.error/ambiguous-registration where it is used; a frame with no app registrations passes [(rf/image {:id :my/empty})]. |
:adapter |
Any value. | None. | Recorded on the frame for tools. Rendering always uses the adapter installed by init!. |
:doc, :tags |
A string; a set of keywords. | None. | Registration metadata, read back with frame-meta. |
:initial-events |
A vector of setup steps. | None. | Events dispatched into the new frame when it is created; see below. |
:flows |
A vector of reg-flow ids. |
None, so no flow runs. | The flows the frame runs on every event, in dependency order. The ids resolve when the frame is made: an unregistered one raises :rf.error/unregistered-flow, and a cycle or overlapping output paths among them raise :rf.error/flow-cycle or :rf.error/flow-path-overlap. See Activation. |
:on-destroy |
One event vector. | None. | The event destroy-frame! runs before the frame is marked dead. |
:fx-overrides |
{fx-id replacement} |
None. | Replaces effect handlers for every event in this frame. The replacement is an fx id or a function; see with-fx-overrides. A per-dispatch override wins. |
:interceptor-overrides |
{interceptor-ref replacement} |
None. | Replaces or removes interceptors in every event's chain in this frame; see Interceptor overrides. A per-dispatch override wins. |
:interceptors |
A vector of interceptor references (an id, or [id arg]). |
None. | Prepended to every event's chain in this frame. |
:drain-depth |
An integer. | 1000 |
The most events one family runs: an external event or dispatch-sync seed plus every event dispatched while it runs. Past it the family halts, its queued events are dropped, :rf.error/drain-depth-exceeded is emitted, and the drain carries on with external input; see dispatch. |
:platform |
:client or :server. |
:client on CLJS, :server on the JVM. |
Decides which :platforms-restricted effects and coeffects run. |
:preset |
:default, :test or :story. |
:default, which sets nothing. |
A bundle of the keys above; see below. |
:rf.cofx/mint-policy |
:live or :strict. |
:live |
This frame's default mint policy. |
:rf.trace/events-retained |
An integer. | configure!'s :trace-buffer (50). |
This frame's trace ring size in development builds. |
:observability |
{:handled-events [<entry>…] :errors [<entry>…]} |
configure!'s :observability. |
The sink policy; see register-observability-sink!. |
:ssr |
A map. | None. | The frame's SSR settings; see Frame :ssr config. |
:url-bound? |
true or false. |
false |
Whether this frame owns the browser URL; see Browser URL listener. |
:url-strategy |
A URL strategy. | The history strategy. | How routes map to URLs; see URL strategies. |
:revalidate-on |
A subset of #{:focus :reconnect}. |
None. | The host signals that revalidate the frame's stale resources; see Revalidation is a frame property. |
:http-interceptors |
A vector of reg-http-interceptor ids. |
None, so no HTTP interceptor runs. | The frame's :rf.http/managed interceptor chain, in order: :before fns run in vector order, :after fns in reverse. The ids resolve when each request is issued, and one with no definition fails that request with :rf.error/unregistered-interceptor. |
:rf.http/stub-only? |
true or false. |
false |
Whether the frame's :rf.http/managed requests are kept off the network. When true, a request no stub transport answers fails as :rf.http/transport. |
:initial-eventsis a vector of steps. A step is an event vector, or{:event [...] :opts {...}}where:optsaredispatch-syncopts without:frame. Each step is dispatched synchronously and drained before the next, andmake-framereturns once they settle. Asynchronous effects they start are not awaited. A single step is still wrapped:[[:app/boot]], not[:app/boot]. See Seeding initial state.- Setup is strict. If a step's handler, an interceptor, a coeffect or a flow throws, the frame is destroyed and
make-framethrows. An effect that throws after its step's:dbcommitted does not fail construction. :preset :testsets:rf.http/stub-only? true,:drain-depth 1000and:rf.cofx/mint-policy :strict;:preset :storysets:rf.http/stub-only? trueand:drain-depth 16. Under either, a:rf.http/managedrequest no stub transport answers fails as:rf.http/transport, with a message namingwith-transportandinstall-transport!. Keys you pass win over the preset's.- A frame config cannot classify
app-dbdata: a config carrying:sensitiveor:largeis rejected. Declare the paths withreg-classificationbeside the feature that owns them; every frame applies the declarations its view resolves. See Keep secrets out of traces. - Any other key is stored with the frame and returned by
frame-meta; nothing reads it, and nothing warns. - The errors a malformed config raises are listed under
make-frame.
Resetting a frame¶
To replace a frame, destroy it with destroy-frame!, which runs :on-destroy and releases per-feature resources, then create it again from the same config:
;; Destroy, then re-create from the same config (which carries :id :rf/default).
;; Run this outside any event handler, for example from a restart button's :on-click.
(rf/destroy-frame! :rf/default)
(rf/make-frame config)
- The new frame starts with an empty
app-dbandruntime-dband runs its:initial-eventsagain; a machine's snapshot staysniluntil the machine next handles an event. - For a frame built from images, pass the same
:imagesvector again; otherwise the new frame gets the default image, which runs every registration. - Flows are part of the config: pass the same
:flowsagain.destroy-frame!drops the frame's flow memo, so the new frame evaluates every flow on its first event; the definitions stay registered. - To empty
app-dband keepruntime-db, dispatch[:rf/set-db {}]instead. Development tools can also call(rf.epoch/replace-frame-state! frame-id {:rf.db/app {}}). - The pair is not atomic.
destroy-frame!has no handler-scope guard, so called from inside a handler it destroys the frame, and the followingmake-framethrows because frames cannot be created inside a handler, leaving the frame destroyed. Frame creation and destruction belong outside handlers anyway. - See Ending and resetting a frame.
destroy-frame!¶
- Kind: function
- Signature:
- Description: Tears down a frame and releases everything it holds.
frame-targetis a frame-id keyword or a live frame value. Calling it again is a no-op.- Queued events that have not started are dropped at once. A handler already running may return, and interceptor
:afterfns already entered may unwind, but their results are discarded: no later framework step or render runs. - A configured
:on-destroyevent, and the events it dispatches to the same frame, run before the frame is marked dead. - A dispatch from elsewhere during teardown may reach the queue, but it is dropped before its handler runs. Afterwards,
dispatchandsubscribeagainst the dead or absent frame do nothing and emit:rf.error/frame-destroyed. - Teardown also releases the frame's feature state: it aborts in-flight managed HTTP requests (their replies are never delivered), cancels pending
:dispatch-laterand machine:aftertimers, and drops flows, machines, schemas, routing and resource caches, SSR state and epoch history. It clears the subscription cache and removes the frame. - A throwing
:on-destroyhandler does not stop teardown: it emits:rf.error/on-destroy-handler-exceptionand the frame is still destroyed. Guard the call todestroy-frame!if destruction must be prevented. - If any cleanup step fails, one
:rf.error/frame-teardown-failedrecord lists the failures (:hook-failures), and the frame is still removed. - A frame value destroys only that frame: if a new frame has since been created under the same id, the old value does nothing. A frame-id keyword destroys whichever frame is live under that id.
- Queued events that have not started are dropped at once. A handler already running may return, and interceptor
- Example:
current-frame-id¶
- Kind: function
- Signature:
- Description: Returns the id of the current frame: the one bound by
with-frameorwith-new-frame, or on CLJS the nearest enclosingframe-providerorframe-root. Outside any frame scope it raises:rf.error/no-frame-context; there is no fallback to:rf/default. - Example:
frame-ids¶
- Kind: function
- Signature:
- Description: Returns the set of live (not destroyed) frame ids. With a string prefix, it keeps the ids whose keyword namespace starts with the prefix; ids with no namespace are left out.
- Example:
frame-meta¶
- Kind: function
- Signature:
- Description: Returns the metadata
make-framerecorded for a frame::idplus the supplied config after preset expansion (:fx-overrides,:interceptors,:ssr,:initial-events, …), merged with lifecycle fields (:created-at, …). Returnsnilfor an unknown or destroyed frame. - Example:
app-db-value¶
- Kind: function
- Signature:
- Description: Returns the frame's current
app-dbas a plain map, not the container, ornilfor an unknown or destroyed frame. Accepts a frame-id keyword or a live frame value. Read a path with(get-in (rf/app-db-value frame-id) path). - Example:
frame-state-value¶
- Kind: function
- Signature:
- Description: Returns the frame's whole state,
{:rf.db/app <app-db> :rf.db/runtime <runtime-db>}, ornilfor an unknown or destroyed frame. Use it for SSR, epochs, time travel and Xray, and to save state for:rf/install-frame-state. A fresh frame's state is{:rf.db/app {} :rf.db/runtime {}}. Readruntime-dbwith(:rf.db/runtime (rf/frame-state-value frame-id)). - Example:
frame-generation¶
- Kind: function
- Signature:
- Description: Returns the frame's generation: the table of registrations the frame is running, resolved from its images, which says which handler answers each
[kind id]. It is fixed ("sealed") as a value, and replaced whole when the frame is created, when its images change, and, in every build, when a registration it selects is added or re-evaluated. Use it to check what a frame composed from several images ended up running; tools such as Pair MCP'sdescribe-imageand Xray read it too.frame-targetis a frame id or a live frame value. One that does not resolve to a live frame carrying a generation raises:rf.error/frame-no-generation.- The map's public keys are
:rf.gen/resolver(the sealed[kind id]map),:rf.gen/images,:rf.gen/kinds, and:rf.gen/shadows. :rf.gen/shadowsis the cross-image shadow report: what a later image overrode in an earlier one, as[{:registration [kind id] :image <defined-in> :shadowed-by <winner>} …], or[]when nothing was shadowed.- See Reading what a frame is running.
- Example:
image¶
- Kind: macro
- Signature:
- Description: Builds an image: a selection of registrations, as inert data, that a frame resolves against. Pass it to
make-frameorframe-rootunder:images. Building an image registers and runs nothing.spechas three public keys::id(optional). Every image in a multi-image:imagesvector needs a distinct:id.:select-ns,{:include [globs] :exclude [globs]}, selects registrations by the namespace they were written in.:includeis a required non-empty vector of strings, and:excludeis optional. In a glob,*is one namespace segment,**is zero or more segments, and*inside a segment matches characters within it ("my-app.**.*-test"). Matching is case-sensitive over the whole namespace. An:includepattern that matches nothing raises:rf.error/image-zero-matchatmake-frame; an:excludepattern that matches nothing is ignored.:registrations, inline registrations in:reg-event,:reg-sub,:reg-fxand:reg-cofxsections. Each entry is[id body]or[id metadata body].- In
:images, a later image wins, and(:rf.gen/shadows (rf/frame-generation f))reports what it overrode. - A registration made through a
reg-*function rather than its macro records no namespace, so:select-nscannot select it unless its metadata carries:ns. - Images select
reg-flowregistrations like any other; a frame runs the ones its:flowsnames. - See Images.
- Errors:
- When the image is built:
:rf.error/invalid-image: any other key, an unsupported section, a malformed entry or a malformed:select-ns.
- At
make-frame::rf.error/image-zero-match: an:includepattern matches no loaded registration.
- When the image is built:
- Example:
Hot-reloading a frame's images¶
Re-evaluating a reg-* form during development updates the live frames that select it; you call nothing. To change which images a frame runs, call make-frame again with the same :id and a new :images vector. Frame memory is kept: app-db, runtime-db, caches and lifecycle continue unchanged, and the frame's generation is replaced:
;; config is the map the frame was created with; change only :images.
(rf/make-frame (assoc config :images [new-image]))
- The call replaces the frame's whole config, not only
:images, so pass the rest of it again; a key left out, such as:fx-overrides, is dropped. - It replaces the whole
:imagesvector, not one member; a non-vector raises:rf.error/make-frame-bad-images. - It changes only the named frame, not other frames sharing an image.
- To see what changed, read
frame-generationbefore and after and compare the two withgeneration-diff:
(let [before (rf/frame-generation :my/frame)
_ (rf/make-frame {:id :my/frame :images [new-image]})
after (rf/frame-generation :my/frame)]
(rf/generation-diff before after))
;; => {:added #{[kind id] …} :changed #{…} :removed #{…} :retained #{…}}
See Hot reload swaps the image, keeps the state.
generation-diff¶
- Kind: function
- Signature:
- Description: Compares two sealed image generations and returns
{:added #{[kind id] …} :changed #{…} :removed #{…} :retained #{…}}. It is pure. Use it onframe-generationvalues read before and after re-callingmake-frame, as shown above.:changedand:retainedhold keys present in both; a key is:changedwhen its resolved descriptor is not=, so an unchanged registration selected through a different image is:retained.
Lifecycle and configure¶
These functions start and stop a re-frame2 process and set process-wide options. An application calls init! once at boot, then creates its frames; it calls configure! only to change a process option. The other functions here are for tests, tools and adapter authors.
init!¶
- Kind: function
- Signature:
- Description: Installs the adapter for your view library, and the runtime capabilities that come with it. Each adapter namespace exports an
adapterVar; require the namespace and pass the Var:(rf/init! reagent-adapter/adapter). It creates no frame: mount one withframe-rootor create one withmake-frame.(init!)with no argument is an arity error: anArityExceptionon the JVM, a compiler warning on ClojureScript.(init! nil)or(init! :reagent)raises:rf.error/no-adapter-specified.- Calling it again with the installed adapter is a no-op. Calling it with a different adapter raises
:rf.error/adapter-already-installedand leaves the installed one in place; calldestroy-adapter!first to switch. Two adapter maps are the same adapter when they carry the same canonical:rf.adapter/*:kind, or when they are the identical map. - Until
init!runs,make-frame,frame-rootand anything else that needs the adapter raise:rf.error/no-adapter-installed. Returnsnil. - The shipped adapter Vars:
re-frame.adapter.reagent/adapter,re-frame.adapter.uix/adapter,re-frame.fresco.substrate/adapter,re-frame.ssr/adapterfor server rendering, andre-frame.substrate.plain-atom/adapter, the headless adapter for tests and scripts on the JVM or Node. - Hot reload is safe with the shipped adapters. Reloading re-evaluates the adapter map with new function identities, but its canonical kind is unchanged, so a
^:dev/after-loadcall stays a no-op. See Hot reload. - A custom adapter with no canonical kind is compared by identity, so re-evaluating its Var and calling
init!again raises. Hold it in adefonce, or calldestroy-adapter!in the after-load fn. - See Boot and mount an app.
- Example:
destroy-adapter!¶
- Kind: function
- Signature:
- Description: Tears down the installed adapter so another can be installed; the counterpart of
init!. Returnsnil.- It releases every Fresco root on the page, whatever adapter is installed, and then runs the adapter's own cleanup, which releases every React root the adapter created. A root whose owner does not render again stays empty until the page reloads.
- A cleanup step that throws does not stop the steps after it. The first failure is rethrown with any later one attached: among its suppressed exceptions on the JVM, and in its
rfAdapterTeardownSecondaryErrorsarray on CLJS. The adapter counts as disposed even when cleanup throws. - It clears only the adapter it tore down, so a late cleanup from the old adapter never clears a new one. With no adapter installed it does nothing.
- Until
init!installs another adapter, anything that needs one raises:rf.error/adapter-disposed.
- Example:
current-adapter¶
- Kind: function
- Signature:
- Description: Returns the installed adapter map, exactly as passed to
rf/init!, ornilwhen no adapter is installed. The map carries the adapter contract fns (:make-state-container,:replace-container!,:make-derived-value, …) and a:kind.- To branch on the substrate, read
(:kind (rf/current-adapter))::rf.adapter/reagent,:rf.adapter/uix,:rf.adapter/fresco,:rf.adapter/plain-atomor:rf.adapter/ssr, ornilfor a custom adapter map with no canonical kind.:rf.adapter/helix,:rf.adapter/reagent-slim,:rf.adapter/uiand:rf.adapter/freehandare reserved, and nothing produces them. - To check whether an adapter is installed, test the map, not
:kind: a custom adapter without a kind is installed while(:kind (rf/current-adapter))readsnil. - In a Fresco app,
:kindnames the substrate the app booted on (normally:rf.adapter/fresco), not the view layer; see re-frame.fresco.
- To branch on the substrate, read
- Example:
configure!¶
- Kind: function
- Signature:
-
Description: Sets process-wide options, usually once at boot. Per-frame settings go in the frame config, and swappable implementations have their own setters; see Where settings live. The key set is closed, and four keys exist:
Key Opts Default What it tunes :epoch-history{:depth N :trace-events-keep N}{:depth 50, :trace-events-keep 50}Development only; ignored in a production build. :depthis the records kept per frame;0turns recording off, and lowering it trims existing history at once.:trace-events-keepis how many of the newest records keep their raw:trace-events. An invalid value is dropped silently. See Configuration.:trace-buffer{:events-retained N}{:events-retained 50}Development only. Event slots in each frame's trace ring: one slot per event, however many trace events its run emitted. 0disables retention; tracing itself stays on. It applies to every frame without its own:rf.trace/events-retained. Opts without a usable:events-retained(negative, non-numeric, or{:depth N}) change nothing and emit:rf.warning/trace-buffer-unrecognised-opts.:elision{:rf.egress/threshold-bytes N}{:rf.egress/threshold-bytes 16384}Size above which an undeclared large string triggers the :rf.warning/large-value-unschema'dadvisory. The value is still forwarded unchanged; replacing it with the:rf.size/large-elidedmarker requires declaring the path:large.0turns the detection off.:observability{:handled-events [<entry>…] :errors [<entry>…]}none declared The process default for production observation sinks. See below. :observabilitytakes the same grammar as a frame's:observability. Precedence is per stream: a frame that declares a stream uses its own entries, a frame that omits it inherits this default's, and{:errors []}on a frame opts that frame out. Each record goes to exactly one source per stream.- A frame that inherits the default's sinks still projects its records under its own classification. A record that belongs to no live frame (emitted outside any frame, or naming a frame that no longer exists) goes to this default's sinks alone, projected with no frame's classification, so its data is redacted as
project-egressdescribes for an unknown frame. Unlike the other keys, an explicitnilclears it, and it is validated when you callconfigure!(:rf.error/bad-frame-classification,:where 'rf/configure!). - An unknown top-level key is ignored, and the known keys in the same map are still applied. The known keys are bare, so a bare or
rf-namespaced unknown key such as:epoch-histroyis treated as a typo: development builds emit:rf.warning/unknown-configure-key, naming every offending key and the known set, and production builds remove the warning. A key in your own namespace (:myapp/thing) passes silently, so a wrapper can handconfigure!a composed config without filtering it. :epoch-historyapplies nothing in a production build, silently, and the other keys still apply.- The argument must be one map. Anything else, including
nil, raises:rf.error/configure-bad-argin every build and applies nothing. The keyed form(rf/configure! :trace-buffer {…})raises it on CLJS and is anArityExceptionon the JVM. - SSR error-projection options (
:public-error-id,:dev-error-detail?) are per-frame, on the frame's:ssrmap. - See The
configure!bucket. - Example:
current-config¶
- Kind: function
- Signature:
- Description: Returns the process-level config in effect, in
configure!'s nested shape. Use it to answer "what is this process running with?" from a tool, a health check or a diagnostic panel.- It reports process values only. A frame's own settings, such as
:rf.trace/events-retainedin its metadata, are not reflected. :epoch-historyis present only in a development build, and:trace-bufferonly when the development trace tooling is (a production bundle omits it). The function never fills in a default for missing code.:observabilityis present only after a process default is declared, and shows it as declared, not a frame's effective policy.- Keys are read one at a time, so the map is not a consistent snapshot across keys, and it may hold values that do not serialise. User-namespaced keys that
configure!accepted are not reported.
- It reports process values only. A frame's own settings, such as
- Example:
features¶
- Kind: function
- Signature:
- Description: Returns every optional feature with its status: a map from feature keyword to the feature's coordinates (
:maven,:require,:spec) merged with its live:loaded?flag. It reads an always-loaded feature registry, with no exception and no classpath probe. The features are:schemas,:machines,:routing,:flows,:http,:ssr,:epochand:resources.- It is the only feature-inspection function. Read the flag you need out of the map; an unknown feature keyword has no entry, so the lookup returns
nil. - To fail at boot rather than on first use, write the check yourself, as in the example. It is one line; don't use
assert, which can be compiled out.
- It is the only feature-inspection function. Read the flag you need out of the map; an unknown feature keyword has no entry, so the lookup returns
- Example:
(rf/features) ;; => {:routing {:maven "day8/re-frame2-routing" :require "re-frame.routing" :spec "Spec 012 (Routing)" :loaded? true} …} (get-in (rf/features) [:routing :loaded?]) ;; => true once re-frame.routing has loaded (when-not (get-in (rf/features) [:routing :loaded?]) (throw (ex-info "re-frame.routing is not loaded" (get (rf/features) :routing))))
Feature registration (re-exports)¶
Each optional feature's registration macros are on this facade, so one require covers every registration. The entries here are pointers: the feature's page documents each macro in full, along with the feature's :fx ids, standard events and standard subscriptions.
The feature itself ships in its own artefact, which must be loaded as its page describes; without it, the macro throws that feature's missing-artefact error: :rf.error/machines-artefact-missing, :rf.error/routing-artefact-missing, :rf.error/flows-artefact-missing, :rf.error/schemas-artefact-missing, :rf.error/ssr-artefact-missing, :rf.error/http-artefact-missing or :rf.error/resources-artefact-missing.
These register process-wide, like reg-event. A frame runs a flow only when its :flows config names it.
Machines → re-frame.machines.md¶
A state machine is registered with one call and is itself an event handler; its transition table is data. Read a machine's {:state :data :tags} snapshot with @(rf/subscribe [:rf/machine machine-id]), and test a tag reactively with @(rf/subscribe [:rf.machine/has-tag? machine-id tag]). The [:rf.machine/spawn …], [:rf.machine/destroy …] and [:raise …] fx are on the machines page, as is the plain-function reg-machine*.
reg-machine¶
- Kind: macro
- Signature:
- Description: Registers a state machine as the event handler for
machine-id, keeping per-element source coordinates for Xray. The optionaloptsmap is registration metadata; its:schemavalidates the dispatched outer event vector. Seereg-machine.
defmachine¶
- Kind: macro
- Signature:
(defmachine name ?docstring machine-spec) - Description: Defines a machine spec as a Var, capturing its source at the definition site so a later
(rf/reg-machine :id name)keeps it. Seedefmachine.
Routing → re-frame.routing.md¶
Routes are data. The current route lives in runtime-db and is read with the :rf/route sub. The routing events (:rf.route/navigate, :rf.route/handle-url-change), fx ([:rf.nav/push-url …], [:rf.nav/replace-url …], [:rf.nav/scroll …]) and the :rf/route sub family are on the routing page. The browser URL listener comes with the frame's :url-bound? lifecycle, installed at creation and removed at destroy.
reg-route¶
- Kind: macro
- Signature:
(reg-route id metadata path) → id - Description: Registers a route: an id to navigate to, a URL path, and metadata carrying match events and guards (
:on-match,:can-leave,:params,:query, …). Seereg-route.
route-link¶
- Kind: component
- Signature:
[rf/route-link {:to :route-id :params {...} :query {...} :fragment "..."} & children] - Description: Renders an
<a href=...>for a route id and dispatches[:rf.route/navigate {:url <href>}]on a plain primary-button click. Modifier-key and middle clicks, and:target/:downloadanchors, are left to the browser. It is registered as the view:route/link. Seeroute-link.
Flows → re-frame.flows.md¶
A flow is derived state: it reads declared frame-state inputs, computes a value with a pure function, and writes it to an app-db output path, recomputing when the inputs change. A frame runs the flows its :flows config names; (rf/clear :flow id) removes a flow.
reg-flow¶
- Kind: macro
- Signature:
- Description: Registers a flow, a derived value kept in
app-dbso handlers can read it.metadatacarries:inputsand:output-path(both required) and optionally:docand the classification keys; a:framekey is refused, because each frame names the flows it runs in its:flowsconfig, and so is a:schemakey, because the output's shape is declared withreg-app-schemaat:output-path.derive-fnis pure. Returnsflow-id. Throws:rf.error/flows-artefact-missingwhenre-frame.flowsis not loaded. Seereg-flow.
Schemas → re-frame.schemas.md¶
Malli schemas attached to app-db paths, validated on writes in development builds and not in production. The introspection functions (app-schemas, app-schema-meta, …) and validator hooks are on the schemas page. To validate an untrusted event payload in every build, set :boundary? true on reg-event.
reg-app-schema¶
- Kind: macro
- Signature:
- Description: Attaches a Malli schema to an
app-dbpath. The path is the registration id, under the registrar kind:app-schema, which makes this the only path-keyedreg-*; the optional metadata map carries:docand open:my/*keys. Registration is frame-agnostic, likereg-event: every frame validates against the schemas it resolves, and a:framethrows:rf.error/app-schema-frame-target. Production builds register the schema but never check it. Seereg-app-schema.
reg-app-schemas¶
- Kind: macro
- Signature:
- Description: Registers many path-to-schema entries in one call, and returns the vector of registered paths. Each entry is its own frame-agnostic
:app-schemaregistration; a frame-id keyword, a frame value or a:frameas the second argument throws:rf.error/app-schema-frame-target. Checked in development builds only, as forreg-app-schema. Seereg-app-schemas.
SSR → re-frame.ssr.md¶
Only the two SSR registration macros, reg-head and reg-error-projector, are on this facade. They resolve to re-frame.ssr when the day8/re-frame2-ssr artefact is on the classpath and throw :rf.error/ssr-artefact-missing otherwise.
Everything else is called on re-frame.ssr: render-to-string, project-error, head-model, head-model->html and hydrate! (the head functions are also on re-frame.ssr.head). Requiring re-frame.ssr is what installs the SSR runtime, so an app that renders on the server already names it. The SSR page also documents the :rf.server/* fx and the :rf/hydrate event; the Ring adapter is on re-frame.ssr.ring.
SSR registers no subscriptions: :rf/head and :rf/public-error are data shapes, read with head-model and project-error (details).
reg-head¶
- Kind: macro
- Signature:
(reg-head id ?metadata head-fn) → id - Description: Registers a head function
(fn [db route] head-model)underid; a route uses it through its:headmetadata. Seereg-head.
reg-error-projector¶
- Kind: macro
- Signature:
(reg-error-projector id ?metadata projector-fn) → id - Description: Registers a projector
(fn [trace-event] :rf/public-error)that turns an error trace into the public error a server response shows, or returnsnilto leave that error to the default projector. A frame selects one with its:ssr {:public-error-id …}metadata. Seereg-error-projector.
HTTP → re-frame.http.md¶
Managed HTTP is one fx, [:rf.http/managed …], with one args map and a closed failure taxonomy. The fx, [:rf.http/managed-abort …] and the failure taxonomy are on the HTTP page. Stub transports (with-transport, install-transport!, route-transport and pending-transport) are on re-frame.http.stub-transport, not this facade; see Testing without a network.
reg-http-interceptor¶
- Kind: macro
- Signature:
(reg-http-interceptor id interceptor-map) → id - Description: Registers an
:rf.http/managedinterceptor definition, for work every request needs, such as an auth header. It belongs to no frame and is registered at the top level; a frame runs it by namingidin its:http-interceptorsconfig, and a:framekey ininterceptor-mapthrows:rf.error/http-bad-interceptor.:before (fn [ctx] ctx')runs on the request side, in the order the frame's vector names the ids;:after (fn [ctx response] response')runs on the response side, in reverse order. Remove a definition, for every frame, with(rf/clear :http-interceptor id). Seereg-http-interceptor.
Resources → re-frame.resources.md¶
Resources are cached server-state reads, and mutations are the writes that update them. Their keyword-addressed events and subscriptions ([:rf.resource/ensure …], [:rf.resource/refetch …], [:rf.resource/change-principal …], [:rf.mutation/execute …], the passive [:rf/route-resource …], :rf.resource/* and :rf.mutation/* subs, …) are on the resources page.
- Focus and reconnect revalidation is the frame's
:revalidate-on #{:focus :reconnect}config key; the frame lifecycle installs and removes the host listeners. See Revalidation is a frame property. (rf/clear :resource id),(rf/clear :mutation id)and(rf/clear :resource-scope id)remove a registration and dispose its per-frame runtime state. That is not cache invalidation, nor the[:rf.mutation/clear …]reset of a mutation instance. See Clearing a registration.
reg-resource¶
- Kind: macro
- Signature:
(reg-resource resource-id metadata request-fn) → resource-id - Description: Registers a resource, a cached read, as data.
metadatacarries the required, fail-closed:scopepolicy and an optional:params-schema;request-fnreturns a managed-HTTP args map. Seereg-resource.
reg-mutation¶
- Kind: macro
- Signature:
(reg-mutation mutation-id metadata request-fn) → mutation-id - Description: Registers a mutation: a named write that, on success, invalidates, patches or populates cached reads. See
reg-mutation.
reg-resource-scope¶
- Kind: macro
- Signature:
(reg-resource-scope scope-id metadata resolve-fn) → scope-id - Description: Registers a named scope resolver that a resource's
:scopepolicy refers to. This is the only arity: the resolve fn is the last argument, andmetadatamust declare:inputs(to read the whole db, declare the root path:{:inputs {:db [:db []]}}). Returnsscope-id. Seereg-resource-scope.
resolve-resource-scope¶
- Kind: function
- Signature:
(resolve-resource-scope db scope-id) → scope or nil - Description: Resolves the named scope resolver against
db. Seeresolve-resource-scope.
Reading a resource's or mutation's runtime state¶
These reads are inspection for tools and tests, so they are called in re-frame.resources rather than through rf/: resource-state and mutation-state.
Reading a registered resource's or mutation's spec¶
Read it with rf/handler-meta and the kind's inner key, as Reading registrations shows.
Enumerating resources and mutations¶
List registered ids with rf/registrations and read the live tables at their reserved runtime-db paths, as Enumerating the whole live table shows.
Instrumentation and listeners¶
There are two ways to observe a running app, with different functions:
- The trace and epoch streams are for development tools. The runtime emits a trace event for each step of a pipeline run (the event handled, each subscription run, each effect, each error) and, per processed event, an epoch record: the event with the frame's state before and after it. It keeps the most recent in per-frame rings (fixed-size buffers that drop the oldest entry), read with
trace-bufferandrf.epoch/epoch-history, and delivers each one synchronously to listeners registered withregister-listener!. Production builds (:advancedwithgoog.DEBUG=false) remove all of it. The epoch (time-travel) functions are also on re-frame.epoch. - Observability sinks work in every build. They receive one record per processed event and one per
:rf.error/*error. Register a sink withregister-observability-sink!and name it in a frame's:observabilitypolicy or the(rf/configure! {:observability …})process default.
See Observability.
register-listener!¶
- Kind: function
- Signature:
- Description: Registers
callback-fnunderidto receive every record the runtime emits onstream, for development tools.streamis:trace(development only, removed from production builds) or:epoch(development only, removed from production builds).:traceevents arrive as emitted, with paths the frame classifies already:rf/redactedor elided and no egress profile applied;:epochrecords hold the frame's state unprojected.- Delivery is synchronous: the callback returns before the next record. A record emitted inside a callback, directly or by a
dispatch-syncthe callback makes, is queued behind the record being delivered, so no callback is ever re-entered. Records emitted while a frame is draining its event queue are held and delivered when the drain ends, before the call that ran it returns, so a listener sees settled state and never runs mid-drain. On the JVM, where emits can race across threads, each listener is called serially and never concurrently with itself, so tool appenders and stateful folds need no locking of their own. - Registering an id again on the same stream replaces the listener. Returns
id. An unknownstreamthrows:rf.error/unknown-listener-stream. - A callback that throws does not stop delivery to other listeners. On
:tracethe exception is reported only by one[re-frame2]line naming the listener, printed to*err*on the JVM andconsole.warnon a JS host; on:epochit emits:rf.epoch.cb/listener-exception. - The
:epochstream's publication rules are under Epoch listeners. - Production code registers a sink with
register-observability-sink!instead; see Report errors in production. - See Write a listener.
- Delivery is synchronous: the callback returns before the next record. A record emitted inside a callback, directly or by a
- Example:
;; Dev-only: tap every trace event the runtime emits (removed from production builds). (rf/register-listener! :trace :my-app/trace-tap (fn [trace-event] (js/console.log (:op-type trace-event) (:operation trace-event)))) ;; Dev-only: epoch publications, including later fills of the same record. (rf/register-listener! :epoch :my-app/epoch-tap (fn [record] (js/console.log (:frame record) (:epoch-id record))))
unregister-listener!¶
- Kind: function
- Signature:
- Description: Removes the listener registered under
idonstream. The test fixtures inre-frame.test-supportreset every listener between tests. - Example:
emit-trace-event!¶
- Kind: function
- Signature:
- Description: Emits a custom trace event into the same stream the framework emits to, for milestones of your own that a tool should see beside the framework's. The framework already emits the events that matter, so use it sparingly.
op-typeis the event's category,operationnames this particular event, andtagsis a map of its data. Keep all three in your own namespace: the:rf.*namespaces belong to the framework.- The runtime stamps
:idand:time, adds the event to the current frame's trace history and delivers it to every:tracelistener, as for a framework event. - Development only: production builds remove the call.
- See Emitting your own trace events.
- Example:
trace-buffer¶
- Kind: function
- Signature:
- Description: Returns the named frame's development trace ring without clearing it: by default one bundle per retained pipeline run; with
{:flat true}, the raw trace events.- Each bundle has the shape
group-by-eventreturns, plus:trace-events. - Returns
[]for a destroyed or unknown frame, and always in production, where the ring is never allocated. - The number of retained events is the
(rf/configure! {:trace-buffer {:events-retained N}})setting, or the frame's own:rf.trace/events-retained. group-by-eventanddomino-bucket, which group trace events into bundles, are onre-frame.trace.projection, not this facade.- See The trace buffer.
- Each bundle has the shape
-
Options: the
optskeys filter what is returned.Key Matches Works on :flattruereturns the raw trace events instead of event bundles.Both :event-idThe bundle's event id, or a flat event's :tags :rf.trace/event-id.Both :originThe dispatch's :origin(:tags :rf.event/origin).Both :dispatch-idThe pipeline run's dispatch id (a flat event's :tags :rf.trace/dispatch-id).Both :since-msLater than this time; a bundle's time is its earliest event's. Both :between [t0 t1]Within this time window, inclusive. Both :predA predicate over the bundle or event. Both :operation,:op-typeAn exact match on the event's :operationor:op-type.Flat :severity:op-typeequal to this value::error,:warningor:info.Flat :sinceA trace :idgreater than this.Flat :handler-id:tags :handler-id.Flat :sourceThe event's :source.Flat :sensitive?The event's :sensitive?stamp:truekeeps sensitive events,falsekeeps the others.Flat Keys combine with AND; an unrecognised key is ignored. - Example:
clear-trace-buffer!¶
- Kind: function
- Signature:
- Description: Empties the retained trace events of the named frame, or of every frame. It clears data, not settings: each ring is re-emptied at its own
:rf.trace/events-retainedcap, so the:trace-bufferdefault and every per-frame override survive. A no-op for an unknown frame and in production. - Example:
sensitive?¶
- Kind: function
- Signature:
- Description: Returns true when
trace-eventis a map with a truthy:sensitive?at the top level (not under:tags). Use it to drop sensitive events before forwarding them. Call it rather than testing:sensitive?yourself, so a malformed value is caught too.- It fails closed:
trueis sensitive;false,niland absent are not; and any other truthy value is also sensitive. The trace-event schema types:sensitive?as a boolean, so a string, keyword or number is a contract violation, and forwarding on a violation is the one outcome that cannot be undone.
- It fails closed:
- Example:
(rf/sensitive? {:sensitive? true}) ;; => true (rf/sensitive? {:sensitive? false}) ;; => false (rf/sensitive? {}) ;; => false ;; A malformed stamp is treated as sensitive, not ignored. (rf/sensitive? {:sensitive? "true"}) ;; => true (rf/sensitive? {:sensitive? :yes}) ;; => true ;; Drop sensitive events when forwarding from a flat trace read. (remove rf/sensitive? (rf/trace-buffer :rf/default {:flat true}))
project-egress¶
- Kind: function
- Signature:
- Description: Returns a record or value prepared for sending off-box: the paths the frame classifies as sensitive are redacted and large values elided, as the chosen egress profile (a named policy for one kind of destination) directs. Call it before handing anything to an off-box destination yourself, or to check what a sink will receive; sinks registered with
register-observability-sink!are handed records already projected. It is the only record-level egress function.- It recognises four record kinds by
:kind::rf.observe/handled-event,:rf.observe/error,:rf.observe/derived-treeand:rf/epoch-record. An input without a recognised:kindis walked as a plain value against the frame's classification. - Projecting an
:rf/epoch-recordneeds epoch, which a production build elides. There the call throws:rf.error/epoch-elided, naming the kind, rather than walking the record as a plain value, which would ship itsapp-dbslots raw. - To project a whole epoch ring, map over it:
(mapv #(rf/project-egress % opts) (rf.epoch/epoch-history frame-id)). The ring and its listeners always hold the raw record, so projecting never affectsrestore-epoch!. See re-frame.epoch. - See Keep secrets out of traces, and Choosing a profile.
- It recognises four record kinds by
-
Options:
optsis closed; an unknown key throws:rf.error/bad-egress-opts, naming it.Key Meaning :rf.egress/profileThe destination, one of the six profiles below. Unset: sensitive values redacted, large values elided. An unknown profile throws :rf.error/unknown-egress-profile.:frameThe frame whose classification applies. Chosen by key presence: an explicit :frame(evennil), else a recognised record's own:frame(evennil), else the current frame. A plain value that happens to carry a:framekey contributes no frame. With no frame known, and:rf.egress/include-sensitive?nottrue, the value becomes:rf/redacted; there is no fallback to:rf/default.:pathThe app-dbpath a plain value was read from, so declarations at or above that path apply inside it:(rf/project-egress (get-in db [:auth]) {:frame :rf/default :path [:auth]}). Without it the value is classified as if it were the wholeapp-db, and[:auth :token]does not match.:query-vFor a value read from a framework subscription such as [:rf/machine id]or[:rf/route], that query vector; classification declared on the machine or route then applies. Ignored for other queries.:rf.egress/include-sensitive?,:rf.egress/include-large?,:rf.egress/include-digests?Override the profile's choice for this call; an explicit value wins over the profile. :rf.egress/threshold-bytesThe large-value size threshold for this call (see configure!'s:elision).:rf.egress/include-fx-args?,:rf.egress/include-runtime-db?,:rf.egress/include-event-args?:rf/epoch-recordonly: trusted-local opt-ins for effect:args, the:rf.db/runtimepartition, and trigger and trace event args. Each defaults to false and enables only its own data;:rf.egress/include-sensitive? trueimplies none of them. On other kinds they are accepted and ignored.The six profiles:
Profile For Sensitive values Large values :rf.egress/off-box-observabilityHosted monitoring Redacted Elided :rf.egress/off-box-toolMCP, AI and other tool connections Redacted Elided :rf.egress/local-redactedOn-box development UI Redacted Elided :rf.egress/local-rawA trusted local operator Sent Sent :rf.egress/ssr-hydrationState the server sends to the browser Redacted Sent, since the page needs them :rf.egress/public-errorErrors shown to a client Redacted Elided No profile includes digests; pass
:rf.egress/include-digests? truefor them.:rf.egress/public-erroralso drops an error record's:exception. Otherwise, profiles with the same settings differ only in the destination they name. - Example:;; Verify what an off-box sink will receive before wiring it. (rf/project-egress {:kind :rf.observe/handled-event :frame :rf/default :event-id :auth/sign-in :event [:auth/sign-in {:password "hunter2"}]} {:rf.egress/profile :rf.egress/off-box-observability}) ;; => {:kind :rf.observe/handled-event :frame :rf/default :event-id :auth/sign-in ...} ;; no :event off-box
register-observability-sink!¶
- Kind: function
- Signature:
- Description: Registers a production observability sink
funder the keywordsink-id, the id a frame's:observability {:handled-events [{:sink <sink-id> :rf.egress/profile …}]}entry names. Use it to send handled events and errors to a monitoring service. A frame's:observabilityhas two streams,:handled-events(one record per processed event) and:errors(one per:rf.error/*error), and each lists the sinks it goes to.freceives one record at a time, already projected under the owning frame's classification and the entry's egress profile, which defaults to:rf.egress/off-box-observability; it does no redaction of its own. A handled-event record carries:kind,:frame,:event-id,:time,:outcomeand:elapsed-ms, plus:effectsand:correlationwhen present, and the:eventvector only under a profile that includes sensitive values, such as:rf.egress/local-raw.- A sink that throws is isolated: the event and the other sinks are unaffected. In a development build it also prints one
[re-frame2]line naming the sink; a production build reports nothing. - Registering the id again replaces the sink. Returns
sink-id. - It works in every build, including CLJS
:advancedwithgoog.DEBUG=false. - See Report errors in production and Declare a sink.
- Example:
unregister-observability-sink!¶
- Kind: function
- Signature:
- Description: Removes the observability sink registered under
sink-id. Returnsnil. - Example:
Reading the epoch ring, rewinding a frame, replaying an epoch and writing frame state outside the event pipeline are tools, so they are called in re-frame.epoch rather than through rf/: epoch-history, restore-epoch!, replay-epoch! and replace-frame-state!.
Registrar queries¶
The registrar holds every registration (events, subs, fx, cofx, interceptors, machines, views, routes, resources) as queryable data, which is what the framework's tools are built on. These are the reads; the writes are the reg-* forms and clear. All of them run on the JVM.
registrations and handler-meta take a query map: {:kind k …} asks what the process has registered, and {:kind k :frame f …} asks what one frame runs. The two answer differently only when a frame is built from images that select part of the registrar.
registrations¶
- Kind: function
- Signature:
- Description: Returns every registration of one kind, with the full metadata map per id: source coordinates,
:sensitive,:rf/machine?,:platforms, the doc string. The argument is always a map of:kindand, optionally,:frame.- Without
:frameit reads the process-wide registrar and never consults a frame's image, so it answers the same inside any frame; this is what a tool inspecting a host application wants. - With
:frame fit returns only the ids that frame runs: those its generation carries (seeframe-generation), or, for a frame made without:images, every registered id except one that two namespaces register.fis a frame-id keyword or a live frame value; one that does not resolve to a live frame raises:rf.error/frame-no-generation. - Any other key, or a non-map argument (usually a leftover positional call), raises
:rf.error/registrar-query-invalid, whose ex-data names the offending keys. A misspelled:frameis refused rather than read as the store. :kind :frameraises:rf.error/registrar-kind-not-queryable, naming the functions to use instead (frame-ids,frame-meta), rather than returning a misleading{}.- Any other
:kindoutside the registrar kinds raises:rf.error/unknown-registry-kind, naming the queryable set. - To filter, use
filteron the result; there is no predicate arity.
- Without
- Example:
handler-meta¶
- Kind: function
- Signature:
- Description: Returns the metadata a
reg-*form recorded for one id, ornil. View registrations include source coordinates (:ns,:line,:column,:file); Pair tools resolvedata-rf2-source-coordDOM annotations to a:filethrough this lookup.- Registrar kinds:
:event,:sub,:fx,:cofx,:interceptor,:view,:route,:head,:error-projector,:app-schema,:flow,:resource,:mutation,:resource-scope.:frameraises, as forregistrations. - The two machine kinds
:machine-guardand:machine-actiontake a 2-vector id:(handler-meta {:kind :machine-guard :id [machine-id guard-id]}). They are derived on demand from the machine's registration and exist only in development builds; they are not frame-targetable, so:framereturnsnilfor them. - The grammar adds
:id, and the errors are those ofregistrations(:rf.error/registrar-query-invalid,:rf.error/frame-no-generation,:rf.error/registrar-kind-not-queryable,:rf.error/unknown-registry-kind). - App-db schemas are the kind
:app-schema, keyed by path;(app-schema-meta {:frame f :path p})in re-frame.schemas reads the same registration a frame resolves.
- Registrar kinds:
- Example:
See also¶
- Events, Subscriptions, Views, Frames, Effects, Coeffects, Interceptors, Run to completion and Observability: the concept guides behind these functions.
- Boot and mount an app and Keep secrets out of traces: the task guides.
- Core glossary.