Reputation: 1473
Is it not allowed to use hooks inside of a Higher Order Component? When I try to do it with this simple pattern I'm getting the error Invalid hook call. Hooks can only be called inside of the body of a function component.
// App.js
import React, { useState } from 'react';
const WithState = (Component) => {
const [state, dispatch] = useState(0);
return () => <Component state={state} dispatch={dispatch} />;
}
const Counter = ({ state }) => {
return (
<div style={{ textAlign: 'center', margin: '0 auto'}}>
{state}
</div>
)
}
const CounterWithState = WithState(Counter);
const App = () => {
return <CounterWithState />;
}
export default App;
Upvotes: 7
Views: 5988
Reputation: 39
Inspired by Rafael Souza's answer, you can make it even cleaner with:
const WithState = (Component) => {
return () => {
const [state, dispatch] = useState(0);
return <Component state={state} dispatch={dispatch} />
}
}
Upvotes: 3
Reputation: 731
I believe you should use the hooks inside the HOC:
const WithState = (Component) => {
const WithStateComponent = () => {
const [state, dispatch] = useState(0);
return <Component state={state} dispatch={dispatch} />;
}
return WithStateComponent;
}
Upvotes: 24