Higher Order Component not working for functional component.
I am trying to create a sample functional HOC. I am using react hook useState and passing the state to the passed component. Below is my code
function HOC(WrapperComponent) {
// outside of return function
const [course] = useState({ id: 0, name: "Raja/Kondla" });
return function() {
return <WrapperComponent course={course} />;
};
}
const Comp = HOC(({ course }) => {
return (
<>
<div>HOC</div>
<div>{course.id}</div>
<div>{course.name}</div>
<div>-------------------</div>
</>
);
});
ReactDOM.render(<Comp />, rootElement);
When I run it I am getting below error.
Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
but if I put below code as HOC working fine.
function HOC(WrapperComponent) {
return function() {
// inside return function
const [course] = useState({ id: 0, name: "Raja/Kondla" });
return <WrapperComponent course={course} />;
};
}
getting the result output:
HOC
0
Raja/Kondla
Can someone explain me what is the reason? and using functional HOC, will there be any performance impact?
Thanks in advance
Your HOC is a function which returns a react component this is why it works when you put the line inside the returned function component.
With that said, I would re-think the need for a HOC when working with hooks, the purpose of HOC's is to share logic across components, hooks solve the same challenge (in a much better way).
It's hard to understand what logic you tried to share with your HOC in your example but i would go for a custom hook instead.
From the DOCS:
Traditionally in React, we’ve had two popular ways to share stateful logic between components: render props and higher-order components. We will now look at how Hooks solve many of the same problems without forcing you to add more components to the tree.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments