Liking cljdoc? Tell your friends :D

com.fulcrologic.fulcro.react.hooks

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`.
raw docstring

*child-index*clj

Atom tracking the current child index for path computation.

Atom tracking the current child index for path computation.
sourceraw docstring

*hook-index*clj

Atom tracking the current hook index within the rendering component.

Atom tracking the current hook index within the rendering component.
sourceraw docstring

*pending-effects*clj

Atom collecting effects to run after render completes.

Atom collecting effects to run after render completes.
sourceraw docstring

*rendered-paths*clj

Atom collecting all component paths rendered in this frame (for cleanup).

Atom collecting all component paths rendered in this frame (for cleanup).
sourceraw docstring

cleanup-unmounted-components!clj

(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.
sourceraw docstring

clear-context-hooks!clj

(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.
sourceraw docstring

get-all-component-pathsclj

(get-all-component-paths)

Get all component paths currently in the hook registry.

Get all component paths currently in the hook registry.
sourceraw docstring

get-context-hook-registryclj

(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.
sourceraw docstring

get-render-callbackclj

(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.
sourceraw docstring

hooks-enabled?clj

(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).
sourceraw docstring

make-rendering-contextclj

(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"}))))
```
sourceraw docstring

mark-mounted!clj

(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.
sourceraw docstring

record-rendered-path!clj

(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.
sourceraw docstring

ref-currentclj/s

(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
```
sourceraw docstring

render-with-hooksclj

(render-with-hooks ctx render-fn)

Render a component within a rendering context, with full hooks support. Sets up all the hook bindings and executes effects after render.

ctx - A context from make-rendering-context render-fn - A zero-arg function that performs the render (e.g., calling a factory)

Returns the result of render-fn.

Example:

(let [ctx (hooks/make-rendering-context)
      factory (comp/factory MyComponent)]
  ;; First render - hooks initialize
  (hooks/render-with-hooks ctx
    (fn [] (factory {:id 1 :name "Test"})))

  ;; Subsequent renders - hooks persist
  (hooks/render-with-hooks ctx
    (fn [] (factory {:id 1 :name "Updated"}))))
Render a component within a rendering context, with full hooks support.
Sets up all the hook bindings and executes effects after render.

`ctx` - A context from `make-rendering-context`
`render-fn` - A zero-arg function that performs the render (e.g., calling a factory)

Returns the result of render-fn.

Example:
```clojure
(let [ctx (hooks/make-rendering-context)
      factory (comp/factory MyComponent)]
  ;; First render - hooks initialize
  (hooks/render-with-hooks ctx
    (fn [] (factory {:id 1 :name "Test"})))

  ;; Subsequent renders - hooks persist
  (hooks/render-with-hooks ctx
    (fn [] (factory {:id 1 :name "Updated"}))))
```
sourceraw docstring

run-pending-effects!clj

(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.
sourceraw docstring

set-ref-current!clj/s

(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
```
sourceraw docstring

set-render-callback!clj

(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.
sourceraw docstring

use-callbackclj/s

(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
sourceraw docstring

use-componentclj/s

(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`.
sourceraw docstring

use-contextclj/s

(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.
sourceraw docstring

use-debug-valueclj/s

(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
sourceraw docstring

use-deferred-valueclj/s

(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
sourceraw docstring

use-effectclj/smacro

(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
sourceraw docstring

use-gcclj/s

(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)))
```
sourceraw docstring

use-generated-idclj/s

(use-generated-id)

Returns a constant ident with a generated ID component.

Returns a constant ident with a generated ID component.
sourceraw docstring

use-idclj/s

(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
sourceraw docstring

use-imperative-handleclj/s

(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
sourceraw docstring

use-insertion-effectclj/s

(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
sourceraw docstring

use-layout-effectclj/s

(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
sourceraw docstring

use-lifecycleclj/smacro

(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)) [])`
sourceraw docstring

use-memoclj/s

(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
sourceraw docstring

use-reducerclj/s

(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
sourceraw docstring

use-refclj/s

(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
sourceraw docstring

use-rootclj/s

(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`.
sourceraw docstring

use-stateclj/s

(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
sourceraw docstring

use-sync-external-storeclj/s

(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
sourceraw docstring

use-transitionclj/s

(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
sourceraw docstring

use-uismclj/s

(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`.
sourceraw docstring

useEffectclj/s

(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
sourceraw docstring

useStateclj/s

(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
sourceraw docstring

with-rendering-contextclj/smacro

(with-rendering-context [ctx] & body)

Macro for convenient isolated component rendering with hooks support. Executes body within a rendering context with all hooks properly bound.

Usage:

(let [ctx (hooks/make-rendering-context)]
  ;; First render
  (hooks/with-rendering-context [ctx]
    (ui-my-component {:id 1}))

  ;; Subsequent render with same context - hooks persist
  (hooks/with-rendering-context [ctx]
    (ui-my-component {:id 1})))

The context must be created outside with make-rendering-context so it can persist across multiple renders (enabling hooks state to accumulate).

For a single-render test, you can also create the context inline:

(hooks/with-rendering-context [(hooks/make-rendering-context)]
  (ui-my-component {:id 1}))
Macro for convenient isolated component rendering with hooks support.
Executes body within a rendering context with all hooks properly bound.

Usage:
```clojure
(let [ctx (hooks/make-rendering-context)]
  ;; First render
  (hooks/with-rendering-context [ctx]
    (ui-my-component {:id 1}))

  ;; Subsequent render with same context - hooks persist
  (hooks/with-rendering-context [ctx]
    (ui-my-component {:id 1})))
```

The context must be created outside with `make-rendering-context` so it can
persist across multiple renders (enabling hooks state to accumulate).

For a single-render test, you can also create the context inline:
```clojure
(hooks/with-rendering-context [(hooks/make-rendering-context)]
  (ui-my-component {:id 1}))
```
sourceraw docstring

cljdoc builds & hosts documentation for Clojure/Script libraries

Keyboard shortcuts
Ctrl+kJump to recent docs
Move to previous article
Move to next article
Ctrl+/Jump to the search field
× close