React Context

UIx wrapps React's Context API to provide seamless experience between ClojureScript and JVM Clojure.

The example below illustrates how Context API can be used in .cljc namespace.

(ns uix.recipes.context
  (:require [uix.core.alpha :as uix.core :refer [defcontext]]))

(defcontext *ctx*)

(defn component [f]
  (let [v (uix.core/context *ctx*)]
    [:button {:on-click f}
     v]))

(defn recipe []
  (let [v (uix.core/state 0)
        f (uix.core/callback #(swap! v inc) [])]
    (uix.core/context-provider [*ctx* @v]
      [component f])))

defcontext is macro that declares a dynamic var which is bound to either React's Context object when compiled into JavaScript or to an optional value when running on JVM.

context-provider is a macro that resembles clojure.core/binding syntax and in fact when running on JVM all it does is creating a binding to a value for provided dynamic var. For ClojureScript the macro emits React's Context provider that binds specified context to the value for a given components sub-tree.

context hook reads current value from the context var.

Last updated