Mark Thomas Miller's logo

How to use React Hooks inside class components

April 22, 2020

If you want to use a React Hook inside of a class component, this is one of the simplest, cleanest approaches you can find. Let's say that you have a class component that looks like this:

class MyClassComponent extends Component {
  render() {
    return <div>{kitten}</div>
  }
}

export default MyClassComponent

The problem is that you need to get the value of kitten from a hook, and per React's spec, hooks can't be used directly inside classes.

We can solve this by creating a function that passes kitten as a prop to the class component. We'll call this function withKitten. Simply wrap the export of the class component with withKitten:

// Change your export from this:
export default MyClassComponent

// To this:
export default withKitten(MyClassComponent)

Then, we need to define this withKitten function. I usually put it in the same file as the class component:

const withKitten = Component = props => {
  const kitten = useSomeHook()
  return <Component kitten={kitten} {...props} />
}

Because withKitten is a function, it can use React Hooks! Its purpose is simply to add kitten to your component as a prop. That means that you can use {this.props.kitten} to access it in your class component:

class MyClassComponent extends Component {
  render() {
    return <div>{this.props.kitten}</div>
  }
}

export default withKitten(MyClassComponent)

This pattern is officially called a higher-order component, or "HOC". React's documentation calls this an "advanced technique", so you get to feel good about yourself after implementing it!

A higher-order component (HOC) is an advanced technique in React for reusing component logic. HOCs are not part of the React API, per se. They are a pattern that emerges from React’s compositional nature. – The React Documentation

You've officially implemented a higher-order component to use a React hook inside of a class. Go make that coffee, order that Chipotle, buy that car, you've earned it.