preact: 10.0.0-alpha.1 - __hooks of undefined with render-to-string
There’s an odd bug when using hooks together with render-to-string
.
What I had was a simple component with the useState
hook. Rendered on the client this was fine, on the server it resulted in: Uncaught TypeError: Cannot read property '__H' of undefined
.
At first I thought this had something to do with render-to-string
because the error also occurred when I replaced preact’s render function on the client with render-to-string
. After some more investigation this wasn’t actually a bug in that library but rather in preact/hooks
, let me explain:
The __H
in the error stands for __hooks
that can’t be read because currentComponent
is undefined. This is defined when you use preact’s render function. In this codesandbox you can see that at first render-to-string
throws the error, after that the same component renders fine (normal render function), then render-to-string
works!
About this issue
- Original URL
- State: closed
- Created 5 years ago
- Comments: 18 (9 by maintainers)
Leaving this for the next person who makes the mistake I made:
If you are new to Preact and you found this bug by searching “Cannot read property ‘__H’ of undefined” on Google: That error message can also happen if you call
useState
and you are not actually in a component function. I recommend enabling “preact/debug”: https://preactjs.com/guide/v10/debugging/Thanks for pointing folks in the right direction @mcclure! I wonder if it would be worth creating a page on preactjs.com that lists out common error messages with fixes for each? That way anyone googling gets a nice resource with a clear answer.
I’ve landed here because of
the cause was vs-code auto-import looking like this
Had a look into this and the issue is that we never set
vnode._component
anywhere inrender-to-string
. This will lead tocurrentComponent
always beingnull
inpreact/hooks
and finally to an exception when we try to accesscurrentComponent.__hooks
a few lines later.@didymu5 yes by using the new version of render-to-string
Was this ever resolved? I still get the undefined error, with a built package. In development the hooks work fine. However, after I build and serve the built .js package, I get the following error.
Fixed in https://github.com/developit/preact-render-to-string/pull/77 👍