How can I use React hooks in React classic `class` component?

Aminadav Glickshtein picture Aminadav Glickshtein · Nov 19, 2018 · Viewed 43.9k times · Source

In this example, I have this react class:

class MyDiv extends React.component
   constructor(){
      this.state={sampleState:'hello world'}
   }
   render(){
      return <div>{this.state.sampleState}
   }
}

The question is if I can add React hooks to this. I understand that React-Hooks is alternative to React Class style. But if I wish to slowly migrate into React hooks, can I add useful hooks into Classes?

Answer

Joel Cox picture Joel Cox · Jan 17, 2019

High order components are how we have been doing this type of thing until hooks came along. You can write a simple high order component wrapper for your hook.

function withMyHook(Component) {
  return function WrappedComponent(props) {
    const myHookValue = useMyHook();
    return <Component {...props} myHookValue={myHookValue} />;
  }
}

While this isn't truly using a hook directly from a class component, this will at least allow you to use the logic of your hook from a class component, without refactoring.

class MyDiv extends React.Component {
  render(){
    const myHookValue = this.props.myHookValue;
    return <div>{myHookValue}</div>;
  }
}

export default withMyHook(MyDiv);