I've a higher order component which accepts another component as a parameter and returns the modified component. I'm new to react and I'm confused regarding the return statement in the code.
import React, { useState } from "react";
const HOC = (OriginalComp) => {
function NewComp() {
const [money, setMoney] = useState(10);
const handleIncrease = () => {
setMoney(money * 2);
};
return <OriginalComp money={money} handleIncrease={handleIncrease} />;
}
return NewComp;
};
export default HOC;
I'm having hard time visualising the return NewComp part and the other return. Does the return NewComp return previous return statement(i.e return <OriginalComp money={money} handleIncrease={handleIncrease} />), or does it simply return NewComp the function?
Concept : Higher-order component is basically a technique in react for reusing component logic. It is basically a pattern which allow us to use Higher order function.
Explanation of your code : The OriginalComp is whatever component needs to display onscreen. It means reusable logic will be execute using following line:
And finally, the HOC function itself is returned at the very bottom of the code snippet (NewComp), because, as I said earlier, HOCs are functions that take in one component and return a new, enhanced component.
Some common examples of HOC's: Common Loader, Common list, etc.