Hacker News new | ask | show | jobs
by spankalee 1128 days ago
Controllers are a much simpler way to hook a component's lifecycle than hooks, and I'm referring to the implementation and conceptual load.

A hook system takes some doing to build, controllers work like:

    connectedCallback() {
      this.controllers.forEach((c) => c.hostConnected());
    }
References from host to controller and controller to host are simple JS references that you can directly see in the debugger.

The React custom hook is a bit shorter, but it's only 13 lines vs 17, and I think hooks are harder to understand because of how much is happening under the hood and the fact that for some reason you need two separate useEffect() calls.

1 comments

In terms of implementation, I can believe you that they're simpler.

In terms of conceptual load I disagree. In React I'd have to know two concepts: `useEffect` and `useState`. In Lit I have to know the API of LitElement; that it implements a host; the four methods of the controller; the boilerplate for registering my controller and triggering updates; plus all the conceptual baggage of classes.

Further, the hooks implementation considers when an effect should replace itself. For example, if you wanted to have the timeout change dynamically based on the component input, you'd get this for free in react by including `[timeout]` in the dependency array of `useEffect`, whereas with the controller you'd have to do the diffing and replacement yourself.

Then there's propagation of errors from controllers through the tree, where Lit just gives up [1].

Granted, you may not need these features for whatever project you're building, so a simpler framework may be perfectly fine. But don't call it Stockholm-syndrome when other projects _do_ need solutions to these problems.

I want to make clear that I'm not just picking these concepts because they're in React. I've used frameworks before React and I found myself naturally wishing for similar solutions. And React is by no means the only framework with such solutions.

---

[1]: https://lit.dev/docs/components/lifecycle/#errors-in-the-upd...

PS: I was counting 10 Lines in React vs 23 in Lit on the ClockController. Although I would of course be fine with both, if I thought it improved on readability.