Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I think that the clearer way to explain hooks is just referencing how they are implemented.

When a function component is called it is called on a "fiber" a stateful representation of the component instance.

This fiber is available to the hook as if it was global variable that is set before the component is rendered.

This is why you cannot call a hook is a setTimeout or a callback to another component: the global fiber is either unset or has a different value.

The other part is that each hook invocation works on a state accessed as sorta fiber.hooks[index++].

So for example you can call hooks in a loop or in conditionals or in synchronous callbacks, but each rendering must be compatible with the first.

Eg

  let s;
  If(Math.random()<0.5) s=useState({});
  else s=useState([])
Should work.

You could also do the same with useEffect if you keep the length/nullness of the dept array.



Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: