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.
JavaScript
x
24
24
1
// App.js
2
import React, { useState } from 'react';
3
4
const WithState = (Component) => {
5
const [state, dispatch] = useState(0);
6
return () => <Component state={state} dispatch={dispatch} />;
7
}
8
9
const Counter = ({ state }) => {
10
return (
11
<div style={{ textAlign: 'center', margin: '0 auto'}}>
12
{state}
13
</div>
14
)
15
}
16
17
const CounterWithState = WithState(Counter);
18
19
const App = () => {
20
return <CounterWithState />;
21
}
22
23
export default App;
24
Advertisement
Answer
I believe you should use the hooks inside the HOC:
JavaScript
1
8
1
const WithState = (Component) => {
2
const WithStateComponent = () => {
3
const [state, dispatch] = useState(0);
4
return <Component state={state} dispatch={dispatch} />;
5
}
6
return WithStateComponent;
7
}
8