Skip to content
Advertisement

React Using useState/Hooks In HOC Causes Error “Hooks can only be called inside of the body of a function component”

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;

Advertisement

Answer

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;
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement