Effects

UIx provides a way to perform side effects in components via React’s effect hook. Effects are useful for making HTTP requests, interacting with DOM or basically performing any kind of impure operation that mutates some global state and might need to be cleaned up later at some point.

effect! function wraps React's useEffect hook and takes care of handling dependencies collection of immutable values that controls update cycle of an effect. More information about effect hook is available in React documentation on effect hook.

In the example below effect callback will execute and update document’s title after every update of the component.

(defn example []
  (let [clicks (uix.core/state 0)]
    (uix.core/effect!
      (fn []
        (set! (.-title js/document)
              (str "Number of clicks: " @clicks))))
    [:button {:on-click #(swap! clicks inc)}
      "increment"]))

Dependencies vector allows conditional execution of an effect. In the example above dependencies are not passed into the effect causing it to execute on every update of the component. Read more about conditional effect execution in React docs.

Macro

UIx provides convenient macro for declaring effects. It takes optional vector of dependencies, any number of forms to be executed in setup phase and optional callback to be executed in cleanup phase of an effect.

(uix.core/with-effect! []
  (println :setup)
  (println :also-setup)
  #(println :cleanup))

Last updated