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)?
Decorators in React help you take an existing Class component, or function of a Class component, and modify it, thereby allowing you to add extra capabilities, without having to mess with the existing codebase. Modification can be overriding the existing function completely, or just adding extra logic to it.
A higher-order component (HOC) is an advanced technique in React for reusing component logic. HOCs are not part of the React API, per se. They are a pattern that emerges from React's compositional nature. Concretely, a higher-order component is a function that takes a component and returns a new component.
Don't Use HOCs inside the render method This means component identity should be consistent across renders. Also, when a component's state changes, React has to calculate if it is necessary to update the DOM. It does this by creating a virtual DOM and comparing it with the current DOM.
Higher-Order Components are not part of the React API. They are the pattern that emerges from React's compositional nature. The component transforms props into UI, and a higher-order component converts a component into another component. The examples of HOCs are Redux's connect and Relay's createContainer.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With