Using the proposed React Hooks in ClojureScript

Yesterday at ReactConf, a proposal was introduced for a new React feature called “Hooks.” More info here: https://reactjs.org/docs/hooks-intro.html

I’m sure I’m not the only one that immediately realized how similar this was to the way reagent components are written :smile:. I personally am perfectly happy to try and get rid of reagent and use (as close to) raw React as possible, and these new features like async rendering, Suspense and (now) Hooks are painting a very bright future for that road.

I decided to whip up a quick demo of it being used in CLJS today:

8 Likes

Very nice demo, I like how simply your use-atom brings Clj(s) atom’s and power to React with just a few lines of code. Very nice way of having global state that’s viewed as local state.

3 Likes

I also gave this idea go, but in reagent.
And not actually using react hooks :stuck_out_tongue: (just something that looks a lot like react hooks)

See here

core.clj for usage
hooks.clj for the implementation of the hooks

3 Likes

My take - very simple:

(ns fun.core
  (:require ["react" :as react]
            ["react-dom" :as react-dom]))

(defn my-counter []
  (let [[count set-count] (react/useState 0)]
    (react/createElement "button"
                         #js{:onClick #(set-count (inc count))}
                         (str "Clicked " count " times"))))

(defn main! []
  (react-dom/render
    (react/createElement my-counter)
    (js/document.getElementById "app")))
2 Likes

@lilactown
One thing I like about your Hx library is that, I can use any third-party react hooks/components with (almost) no changes directly. I played around with it.
https://github.com/oneto018/shadow-cljs-react.
I successfully ported this code https://codesandbox.io/s/k92ymrxw3
to clojurescript with little changes
https://github.com/oneto018/shadow-cljs-react/blob/0c65f904b12abf682a2ead409ed9c01b769fd9d3/src/main/acme/app/counter.cljs#L48. There is a little friction because of js object/clojurescript maps differences. But mostly it was straightforward.

2 Likes

Relevant links: https://juxt.pro/blog/posts/react-hooks-raw.html and https://github.com/pesterhazy/cljs-react-hooks

1 Like

I wanted to play with, but it seems it requires shadow-cljs to work? I tried with the official cljs compiler with no luck.

If you’re referring to the second link I posted, no - it only requires the Clojure CLI tools.

At the moment shadow-cljs is the easiest way to work with npm based dependencies directly. Yes my example is built using shadow-cljs. Because it uses some npm libraries not available in cljsjs

what’s the current status? that’s the best way using React hooks?

Worked on my own wrapper on React hooks recently. If anyone interested:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.