React hooks wrappers and helpers. The wrappers are simple API simplifications that help when using hooks from Clojurescript, but this namespace also includes utilities for using Fulcro's data/network management from raw React via hooks.
See use-root, use-component, and use-uism.
React hooks wrappers and helpers. The wrappers are simple API simplifications that help when using hooks from Clojurescript, but this namespace also includes utilities for using Fulcro's data/network management from raw React via hooks. See `use-root`, `use-component`, and `use-uism`.
Atom tracking the current child index for path computation.
Atom tracking the current child index for path computation.
Atom tracking the current hook index within the rendering component.
Atom tracking the current hook index within the rendering component.
Atom collecting effects to run after render completes.
Atom collecting effects to run after render completes.
Atom bound while a render (and its effects) is in progress. A render requested meanwhile (e.g. by a state setter called from an effect) sets it to true instead of rendering re-entrantly; the renderer renders again once the current render is complete, like React batching updates from effects.
Atom bound while a render (and its effects) is in progress. A render requested meanwhile (e.g. by a state setter called from an effect) sets it to true instead of rendering re-entrantly; the renderer renders again once the current render is complete, like React batching updates from effects.
Atom collecting all component paths rendered in this frame (for cleanup).
Atom collecting all component paths rendered in this frame (for cleanup).
(cleanup-unmounted-components! prev-paths current-paths)Clean up effects for components that were not rendered in this frame. Called by headless.clj after render completes.
Clean up effects for components that were not rendered in this frame. Called by headless.clj after render completes.
(clear-context-hooks! ctx)Clear all hooks from a rendering context. Useful for test isolation between renders.
Clear all hooks from a rendering context. Useful for test isolation between renders.
(get-all-component-paths)Get all component paths currently in the hook registry.
Get all component paths currently in the hook registry.
(get-context-hook-registry ctx)Get the hook registry from a rendering context. Useful for inspecting hook state in tests.
Get the hook registry from a rendering context. Useful for inspecting hook state in tests.
(get-render-callback ctx)Get the render callback from a context, if one is set.
Get the render callback from a context, if one is set.
(headless-use-id)Headless use-id: an id that is stable for the component's path and hook index, and unique in the app.
Headless `use-id`: an id that is stable for the component's path and hook index, and unique in the app.
(headless-use-reducer reducer initial-arg init)Headless use-reducer: returns [state dispatch]. dispatch is stable and applies the reducer of
the latest render to the current state; the initial state is (init initial-arg) when init is given.
Headless `use-reducer`: returns `[state dispatch]`. `dispatch` is stable and applies the reducer of the latest render to the current state; the initial state is `(init initial-arg)` when `init` is given.
(headless-use-state initial-value)Headless use-state: returns [value setter], with a setter that is stable across renders.
Headless `use-state`: returns `[value setter]`, with a setter that is stable across renders.
(hooks-enabled?)Returns true if hooks infrastructure is active (we're in a headless render with app bound).
Returns true if hooks infrastructure is active (we're in a headless render with app bound).
(make-rendering-context)Create a minimal context for isolated component rendering with hooks support. This creates a mock 'app' structure that provides just enough to make hooks work, without the overhead of a full headless test app.
Returns a context map that can be used with render-with-hooks.
Example:
(let [ctx (hooks/make-rendering-context)]
(hooks/render-with-hooks ctx
(fn [] (ui-my-component {:some "props"}))))
Create a minimal context for isolated component rendering with hooks support.
This creates a mock 'app' structure that provides just enough to make hooks work,
without the overhead of a full headless test app.
Returns a context map that can be used with `render-with-hooks`.
Example:
```clojure
(let [ctx (hooks/make-rendering-context)]
(hooks/render-with-hooks ctx
(fn [] (ui-my-component {:some "props"}))))
```(mark-mounted! path)Mark a component as mounted (no longer in first render). Called by headless.clj after component renders.
Mark a component as mounted (no longer in first render). Called by headless.clj after component renders.
(record-rendered-path! path)Record that a path was rendered in this frame. Called by headless.clj during render traversal.
Record that a path was rendered in this frame. Called by headless.clj during render traversal.
(ref-current ref)Get the current value of a ref. Works in both CLJ and CLJS. This is a CLJC-compatible alternative to (.-current ref).
Usage:
(let [my-ref (use-ref 0)]
(ref-current my-ref)) ;; => 0
Get the current value of a ref. Works in both CLJ and CLJS. This is a CLJC-compatible alternative to (.-current ref). Usage: ``` (let [my-ref (use-ref 0)] (ref-current my-ref)) ;; => 0 ```
(render-with-hooks ctx render-fn)Calls render-fn (a zero-arg fn) inside a hook context for ctx (from make-rendering-context):
it binds the hook bindings with the root path [], then cleans up components not seen and runs
the effects collected while render-fn ran. Returns the result of render-fn.
It does NOT render components. Calling a factory only creates a component instance, so a
render-fn like (fn [] (factory props)) runs no component code and no hooks. Hooks only run
here if render-fn itself runs hook code at the root path (e.g. a hook-using fn called directly).
To render a component with working hooks, use com.fulcrologic.fulcro.headless/render-component
(or render-component-hiccup) with the same ctx, or headless/mount-component for automatic
re-render on state changes.
Calls `render-fn` (a zero-arg fn) inside a hook context for `ctx` (from `make-rendering-context`): it binds the hook bindings with the root path `[]`, then cleans up components not seen and runs the effects collected while `render-fn` ran. Returns the result of `render-fn`. It does NOT render components. Calling a factory only creates a component instance, so a `render-fn` like `(fn [] (factory props))` runs no component code and no hooks. Hooks only run here if `render-fn` itself runs hook code at the root path (e.g. a hook-using fn called directly). To render a component with working hooks, use `com.fulcrologic.fulcro.headless/render-component` (or `render-component-hiccup`) with the same `ctx`, or `headless/mount-component` for automatic re-render on state changes.
(run-pending-effects!)Execute all pending effects collected during render. Runs cleanup (destroy) functions first, then setup (create) functions. Called by headless.clj after render completes.
Execute all pending effects collected during render. Runs cleanup (destroy) functions first, then setup (create) functions. Called by headless.clj after render completes.
(set-ref-current! ref value)Set the current value of a ref. Works in both CLJ and CLJS. This is a CLJC-compatible alternative to (set! (.-current ref) value).
Usage:
(let [my-ref (use-ref 0)]
(set-ref-current! my-ref 42)
(ref-current my-ref)) ;; => 42
Set the current value of a ref. Works in both CLJ and CLJS. This is a CLJC-compatible alternative to (set! (.-current ref) value). Usage: ``` (let [my-ref (use-ref 0)] (set-ref-current! my-ref 42) (ref-current my-ref)) ;; => 42 ```
(set-render-callback! ctx callback)Set a render callback on a context. Called by state setters after updating state. Used internally by mount-component to enable auto-re-render.
Set a render callback on a context. Called by state setters after updating state. Used internally by mount-component to enable auto-re-render.
(use-callback cb)(use-callback cb deps)A simple wrapper around React/useCallback. Converts args to js array before send.
React docs: https://reactjs.org/docs/hooks-reference.html#usecallback
A simple wrapper around React/useCallback. Converts args to js array before send. React docs: https://reactjs.org/docs/hooks-reference.html#usecallback
(use-component app
component
{:keys [initialize? initial-params keep-existing?]
:or {initial-params {}}
:as options})Use Fulcro from raw React. This is a Hook effect/state combo that will connect you to the transaction/network/data
processing of Fulcro, but will not rely on Fulcro's render. Thus, you can embed the use of the returned props in any
stock React context. Technically, you do not have to use Fulcro components for rendering, but they are necessary to define the
query/ident/initial-state for startup and normalization. You may also use this within normal (Fulcro)
components to generate dynamic components on-the-fly (see nc).
The arguments are:
app - A Fulcro app
component - A component with query/ident. Queries MUST have co-located normalization info. You
can create this with normal defsc or as an anonymous component via raw.components/nc.
options - A map of options, containing:
:initial-params - The parameters to use when getting the initial state of the component. See comp/get-initial-state.
If no initial state exists on the top-level component, then an empty map will be used. This will mean your props will be
empty to start.initialize? - A boolean (default true). If true then the initial state of the component will be used to pre-populate the component's state
in the app database.:keep-existing? - A boolean. If true, then the state of the component will not be initialized if there
is already data at the component's ident (which will be computed using the initial state params provided, if
necessary).:ident - Only needed if you are NOT initializing state, AND the component has a dynamic ident.Returns the props from the Fulcro database. The component using this function will automatically refresh after Fulcro transactions run (Fulcro is not a watched-atom system. Updates happen at transaction boundaries).
MAY return nil if no data is at that component's ident.
See also use-root.
Use Fulcro from raw React. This is a Hook effect/state combo that will connect you to the transaction/network/data
processing of Fulcro, but will not rely on Fulcro's render. Thus, you can embed the use of the returned props in any
stock React context. Technically, you do not have to use Fulcro components for rendering, but they are necessary to define the
query/ident/initial-state for startup and normalization. You may also use this within normal (Fulcro)
components to generate dynamic components on-the-fly (see `nc`).
The arguments are:
`app` - A Fulcro app
`component` - A component with query/ident. Queries MUST have co-located normalization info. You
can create this with normal `defsc` or as an anonymous component via `raw.components/nc`.
`options` - A map of options, containing:
* `:initial-params` - The parameters to use when getting the initial state of the component. See `comp/get-initial-state`.
If no initial state exists on the top-level component, then an empty map will be used. This will mean your props will be
empty to start.
* `initialize?` - A boolean (default true). If true then the initial state of the component will be used to pre-populate the component's state
in the app database.
* `:keep-existing?` - A boolean. If true, then the state of the component will not be initialized if there
is already data at the component's ident (which will be computed using the initial state params provided, if
necessary).
* `:ident` - Only needed if you are NOT initializing state, AND the component has a dynamic ident.
Returns the props from the Fulcro database. The component using this function will automatically refresh after Fulcro
transactions run (Fulcro is not a watched-atom system. Updates happen at transaction boundaries).
MAY return nil if no data is at that component's ident.
See also `use-root`.
(use-context ctx)A simple wrapper around the RAW React/useContext. You should probably prefer the context support from c.f.f.r.context.
A simple wrapper around the RAW React/useContext. You should probably prefer the context support from c.f.f.r.context.
(use-debug-value value)(use-debug-value value formatter)A simple wrapper around React/useDebugValue.
React docs: https://reactjs.org/docs/hooks-reference.html#uselayouteffect
A simple wrapper around React/useDebugValue. React docs: https://reactjs.org/docs/hooks-reference.html#uselayouteffect
(use-deferred-value value)A simple wrapper around React/useDeferredValue.
React docs: https://reactjs.org/docs/hooks-reference.html#usedeferredvalue
A simple wrapper around React/useDeferredValue. React docs: https://reactjs.org/docs/hooks-reference.html#usedeferredvalue
(use-effect f)(use-effect f dependencies)A simple macro wrapper around React/useEffect that does compile-time conversion of dependencies to a js-array
for convenience without affecting performance.
React docs: https://reactjs.org/docs/hooks-reference.html#useeffect
A simple macro wrapper around React/useEffect that does compile-time conversion of `dependencies` to a js-array for convenience without affecting performance. React docs: https://reactjs.org/docs/hooks-reference.html#useeffect
(use-gc this-or-app ident edges)Effect handler. Creates an effect that will garbage-collect the given ident from fulcro app state on cleanup, and
will follow any edges (a set of keywords) and remove any things pointed through those keywords as well. See
normalized-state's remove-entity.
(defsc NewRoot [this props]
{:use-hooks? true}
(let [generated-id (hooks/use-generated-id)
f (use-fulcro-mount this {:child-class SomeChild
:initial-state-params {:id generated-id})]
;; will garbage-collect the floating root child on unmount
(use-gc this [:child/id generated-id] #{})
(f props)))
Effect handler. Creates an effect that will garbage-collect the given ident from fulcro app state on cleanup, and
will follow any `edges` (a set of keywords) and remove any things pointed through those keywords as well. See
normalized-state's `remove-entity`.
```
(defsc NewRoot [this props]
{:use-hooks? true}
(let [generated-id (hooks/use-generated-id)
f (use-fulcro-mount this {:child-class SomeChild
:initial-state-params {:id generated-id})]
;; will garbage-collect the floating root child on unmount
(use-gc this [:child/id generated-id] #{})
(f props)))
```
(use-generated-id)Returns a constant ident with a generated ID component.
Returns a constant ident with a generated ID component.
(use-id)A simple wrapper around React/useId. See also use-generated-id, which is a Fulcro-specific function for generating random uuids.
React docs: https://reactjs.org/docs/hooks-reference.html#useid
A simple wrapper around React/useId. See also use-generated-id, which is a Fulcro-specific function for generating random uuids. React docs: https://reactjs.org/docs/hooks-reference.html#useid
(use-imperative-handle ref f)(use-imperative-handle ref f args)A simple wrapper around React/useImperativeHandle.
React docs: https://react.dev/reference/react/useImperativeHandle
A simple wrapper around React/useImperativeHandle. React docs: https://react.dev/reference/react/useImperativeHandle
(use-insertion-effect didUpdate)A simple wrapper around React/useInsertionEffect.
React docs: https://reactjs.org/docs/hooks-reference.html#useinsertioneffect
A simple wrapper around React/useInsertionEffect. React docs: https://reactjs.org/docs/hooks-reference.html#useinsertioneffect
(use-layout-effect f)(use-layout-effect f args)A simple wrapper around React/useLayoutEffect.
React docs: https://reactjs.org/docs/hooks-reference.html#uselayouteffect
A simple wrapper around React/useLayoutEffect. React docs: https://reactjs.org/docs/hooks-reference.html#uselayouteffect
(use-lifecycle setup)(use-lifecycle setup teardown)A macro shorthand that evaluates to low-level js at compile time for
(use-effect (fn [] (when setup (setup)) (when teardown teardown)) [])
A macro shorthand that evaluates to low-level js at compile time for `(use-effect (fn [] (when setup (setup)) (when teardown teardown)) [])`
(use-memo value-factory-fn)(use-memo value-factory-fn dependencies)A simple wrapper around React/useMemo. Converts args to js array before send.
NOTE: React does NOT guarantee it won't re-create the value during the lifetime of the component, so it is sorta crappy in terms of actual memoization. Purely for optimizations, not for guarantees.
React docs: https://reactjs.org/docs/hooks-reference.html#usememo
A simple wrapper around React/useMemo. Converts args to js array before send. NOTE: React does NOT guarantee it won't re-create the value during the lifetime of the component, so it is sorta crappy in terms of actual memoization. Purely for optimizations, not for guarantees. React docs: https://reactjs.org/docs/hooks-reference.html#usememo
(use-reducer reducer initial-arg)(use-reducer reducer initial-arg init)A simple wrapper around React/useReducer. Returns a cljs vector for easy destructuring
React docs: https://reactjs.org/docs/hooks-reference.html#usecontext
A simple wrapper around React/useReducer. Returns a cljs vector for easy destructuring React docs: https://reactjs.org/docs/hooks-reference.html#usecontext
(use-ref)(use-ref value)A simple wrapper around React/useRef.
React docs: https://reactjs.org/docs/hooks-reference.html#useref
A simple wrapper around React/useRef. React docs: https://reactjs.org/docs/hooks-reference.html#useref
(use-root app
root-key
component
{:keys [initialize? keep-existing? initial-params] :as options})Use a root key and component as a subtree managed by Fulcro from raw React. The root-key must be a unique
(namespace recommended) key among all keys used within the application, since the root of the database is where it
will live.
The component should be a real Fulcro component or a generated normalizing component from nc (or similar).
Returns the props (not including root-key) that satisfy the query of component. MAY return nil if no data is available.
See also use-component.
Use a root key and component as a subtree managed by Fulcro from raw React. The `root-key` must be a unique (namespace recommended) key among all keys used within the application, since the root of the database is where it will live. The `component` should be a real Fulcro component or a generated normalizing component from `nc` (or similar). Returns the props (not including `root-key`) that satisfy the query of `component`. MAY return nil if no data is available. See also `use-component`.
(use-state initial-value)A simple wrapper around React/useState. Returns a cljs vector for easy destructuring.
initial-value can be a function.
React docs: https://reactjs.org/docs/hooks-reference.html#usestate
A simple wrapper around React/useState. Returns a cljs vector for easy destructuring. `initial-value` can be a function. React docs: https://reactjs.org/docs/hooks-reference.html#usestate
(use-sync-external-store subscribe get-snapshot)(use-sync-external-store subscribe get-snapshot get-server-ss)A simple wrapper around React/useSyncExternalStore.
React docs: https://reactjs.org/docs/hooks-reference.html#usesyncexternalstore
A simple wrapper around React/useSyncExternalStore. React docs: https://reactjs.org/docs/hooks-reference.html#usesyncexternalstore
(use-transition value)A simple wrapper around React/useTransition.
React docs: https://reactjs.org/docs/hooks-reference.html#usetransition
A simple wrapper around React/useTransition. React docs: https://reactjs.org/docs/hooks-reference.html#usetransition
(use-uism app state-machine-definition id options)Use a UISM as an effect hook. This will set up the given state machine under the given ID, and start it (if not already started). Your initial state handler MUST set up actors and otherwise initialize based on options.
If the machine is already started at the given ID then this effect will send it an :event/remounted event.
You MUST include :componentName in each of your actor's normalizing component options (e.g. (nc query {:componentName ::uniqueName}))
because UISM requires component appear in the component registry (components cannot be safely stored in app state, just their
names).
options is a map that can contain ::uism/actors as an actor definition map (see begin!). Any other keys in options
are sent as the initial event data when the machine is started.
Returns a map that contains the actor props (by actor name) and the current state of the state machine as :active-state.
Use a UISM as an effect hook. This will set up the given state machine under the given ID, and start it (if not
already started). Your initial state handler MUST set up actors and otherwise initialize based on options.
If the machine is already started at the given ID then this effect will send it an `:event/remounted` event.
You MUST include `:componentName` in each of your actor's normalizing component options (e.g. `(nc query {:componentName ::uniqueName})`)
because UISM requires component appear in the component registry (components cannot be safely stored in app state, just their
names).
`options` is a map that can contain `::uism/actors` as an actor definition map (see `begin!`). Any other keys in options
are sent as the initial event data when the machine is started.
Returns a map that contains the actor props (by actor name) and the current state of the state machine as `:active-state`.(useEffect f)(useEffect f deps)A CLJC wrapper around js/React.useEffect that does NO conversion of dependencies. You probably want the macro use-effect instead.
React docs: https://reactjs.org/docs/hooks-reference.html#useeffect
A CLJC wrapper around js/React.useEffect that does NO conversion of dependencies. You probably want the macro use-effect instead. React docs: https://reactjs.org/docs/hooks-reference.html#useeffect
(useState initial-value)A simple CLJC wrapper around React/useState. Returns a JS vector for speed. You probably want use-state, which is more convenient.
React docs: https://reactjs.org/docs/hooks-reference.html#usestate
A simple CLJC wrapper around React/useState. Returns a JS vector for speed. You probably want use-state, which is more convenient. React docs: https://reactjs.org/docs/hooks-reference.html#usestate
(with-rendering-context [ctx] & body)Executes body inside a hook context for ctx (see render-with-hooks, which this wraps):
the hook bindings are established, and effects collected while body runs execute afterwards.
It does NOT render components: (ui-my-component {:id 1}) in body only creates a component
instance, so the component's render and hooks do not run.
To render a component with working hooks, use com.fulcrologic.fulcro.headless/render-component
(or render-component-hiccup) with a context from make-rendering-context, or
headless/mount-component for automatic re-render on state changes:
(let [ctx (hooks/make-rendering-context)]
(headless/render-component-hiccup ctx (ui-my-component {:id 1})))
Executes `body` inside a hook context for `ctx` (see `render-with-hooks`, which this wraps):
the hook bindings are established, and effects collected while `body` runs execute afterwards.
It does NOT render components: `(ui-my-component {:id 1})` in `body` only creates a component
instance, so the component's render and hooks do not run.
To render a component with working hooks, use `com.fulcrologic.fulcro.headless/render-component`
(or `render-component-hiccup`) with a context from `make-rendering-context`, or
`headless/mount-component` for automatic re-render on state changes:
```clojure
(let [ctx (hooks/make-rendering-context)]
(headless/render-component-hiccup ctx (ui-my-component {:id 1})))
```cljdoc builds & hosts documentation for Clojure/Script libraries
| Ctrl+k | Jump to recent docs |
| ← | Move to previous article |
| → | Move to next article |
| Ctrl+/ | Jump to the search field |