This page is not created by, affiliated with, or supported by Slack Technologies, Inc.
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.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?
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.
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.)