Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React js - What is the difference betwen HOC and decorator

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)?

like image 491
itay312 Avatar asked Feb 08 '18 13:02

itay312


People also ask

What is decorator in Reactjs?

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.

What is hoc in React JS?

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.

Should I use Hoc in React?

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.

What is hoc in React with example?

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.


1 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/

like image 120
Jeff P Chacko Avatar answered Sep 19 '22 14:09

Jeff P Chacko