3 ms·
Hooks, and algebraic effects more generally, made a lot more sense to me when I realized they’re really syntactic sugar for a pretty common and useful pattern.
by btown 6y ago
Hooks, and algebraic effects more generally, made a lot more sense to me when I realized they’re really syntactic sugar for a pretty common and useful pattern.
Imagine, for a moment, that every React functional component was passed context as an argument. It’s a black box that you can only interact with through a few public methods - ctx.useState, etc.
For consistency, since we are likely to wrap these in higher order utilities, let’s make them functions not methods: useState(ctx, ...)
Now, it would be annoying to pass ctx around to every prop. So since JS is single-threaded, you could validly use the hack: let’s just store the current value of ctx before calling our component code, then it can be implicit at the call site.
And you might implement this as a decorator (@ annotation) that wraps your component, which you can do in Python. But that’s redundant too since the presence of hooks implies the need for it. So magically imply that wrapper if it’s needed.
That’s it. That’s hooks. It’s the same pattern as “accept a bound function/callback as an argument” except React does the binding for you and places it in the argument list for you. All you need to do is use it.