
Higher Order Component
A higher-order component is a function that takes a component and returns a new component. A higher-order component (HOC) is the advanced technique in React.js for reusing a component logic. 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 create Container.
Syntax:
const EnhancedComponent = higherOrderComponent(WrappedComponent);
Let see it in example:
Now I am going to create two components.
Click.js
import React, { useState } from 'react'; function Click(props) { const [click, setClick] = useState(0); const increase = () => { setClick(click + 1); } return ( <div> <button onClick={increase}> Click{click} times</button> </div> ) } export default Click;
Hover.js
import React, { useState } from 'react'; function Hover(props) { const [click, setClick] = useState(0); const increase = () => { setClick(click + 1); } return ( <div> <h2 onMouseOver={increase}>The {props.name} Hovered {click} times</h2> </div> ) } export default Hover;
In the Click Component and Hover Component we gave the logic separately. By using the HOC function we are reusing a component Click and Hover’s logic.
Click.js
import React, { useState } from 'react'; import NewComponent from './Hoc'; function Click(props) { const {click,increase}=props return ( <div> <button onClick={increase}> The {props.name}Click{click} times</button> </div> ) } export default NewComponent(Click);
Hover.js
import React, { useState } from 'react'; import UpdatedComponent from './Hoc'; function Hover(props) { const {click,increase}=props return ( <div> <h2 onMouseOver={increase}>The {props.name} Hovered {click} times</h2> </div> ) } export default NewComponent(Hover);
By using the HOC method now we compined the both component's logic.
import React from 'react'; import { useState } from 'react'; const NewComponent = OriginalComponent => { function UpdatedComponent() { const [click, setClick] = useState(0); const increase = () => { setClick(click + 1); } return <OriginalComponent name="Mouse" click={click} increase={increase}/> } return UpdatedComponent } export default NewComponent ;
In App.js import the Click and Hover components.
import Click from './Components/HOC/ClickCounter.js'; import Hover from './Components/HOC/Hover.js function App() { return ( <div className="App"> <Click/> <Hover/> </div> ); } export default App;