Fork me on GitHub
#reagent
<
2024-04-06
>
bringe20:04:35

Hello 👋. I'm trying to use react/useEffect inside of a reagent component, and I'm getting this error:

Invalid hook call. Hooks can only be called inside of the body of a function component.
I see an example on the reagent site like this:
(defn todo-edit [props]
  (let [ref (react/useRef)]
    (react/useEffect (fn []
                       (.focus (.-current ref))
                       js/undefined))
    [todo-input (assoc props :input-ref ref)]))
My code is like this:
(defn repl-output []
  (react/useEffect (fn []
                     (prn "highlighting code blocks")
                     (.. js/window -hljs (highlightAll))))
  [:pre [:code {:class "language-clojure"} ":hello"]])

(defn main []
  (rdom.client/render (rdom.client/create-root (js/document.getElementById "output")) [repl-output]))
What am I doing wrong? I'm not seeing a difference between the two that would cause this error.

p-himik20:04:13

Notice how todo-edit is used in the Reagent example.

bringe20:04:34

Ahh I'm guessing the :f> is significant here. Can you explain a bit more about the difference in that and what I've done?

bringe20:04:02

Been a while since I've done much FE dev

p-himik20:04:46

That denotes that todo-edit is a function component, and you need a function component to be able to use hooks, just as the error states. It's all meticulously documented in Reagent docs in its repo.

bringe20:04:12

Got it. Thanks!

bringe20:04:12

Found it discussed https://cljdoc.org/d/reagent/reagent/1.2.0/doc/tutorials/react-features#function-components. (Linking in case it's useful to someone else in the future who reads this.)

bringe21:04:04

Changing [repl-output] to [:f> repl-output] in the main function above fixed my issue 🎉

👍 1