Can someone explain what is the difference between these two? I mean except the syntactic difference, do both of these techniques are used to achieve the same thing (which is to reuse component logic)?
3 Answers
For all practical reasons, decorators and HOC (Higher-Order-Component aka Wrapper) do the same thing.
One major difference is that, once you add a decorator, the property/class can only be used in it's decorated form. HOC pattern leaves higher order as well as the lower order components available for use.
For further reading on decorators -> https://medium.com/google-developers/exploring-es7-decorators-76ecb65fb841
Decorators isn't a widely implemented JS feature. It is still in its proposal stage. Babel 7 by default allows decorators as a default plugin in their stage 0 configuration.
https://babeljs.io/docs/plugins/transform-decorators/
I also am curious why the React community calls this Higher-Order Component (HOC) instead of Decorator pattern, which seems to be what it exactly is doing and has been described in 1994 (!) by the Gang of Four (GoF): Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides.
An additional source of confusion is that ES7's decorator pattern is different than GoF's explanation of Decorator pattern. It is unfortunate that that is the case. I'd have hoped that instead of redefining an existing term, it'd be preferable to reuse the term even while qualifying it. And even if that's not possible, inventing a different term would be more acceptable.
-
2Decorators in EcmaScript are not a pattern, but a language feature, just like variables, function, classes, etc are language features. There is no confusion if you understand the difference between a pattern and a language feature. Also, the name makes sense for both the pattern and language feature because in both cases decorators decorate existing code with extra functionality without modifying that code directly.– MihailJun 1, 2020 at 11:57
Two differences would be decorators are used to mutate the variable while HOC's are recommended not to. Another is specific to React, HOC's are supposed to render a component, while decorators can return different things depending on implementation.