How to use React Hooks inside class components

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! You should feel pretty darn good about yourself.

About the author

I'm Mark Thomas Miller, a full stack engineer and designer currently working at ConvertKit. (We're hiring!) People like Arnold Schwarzenegger, Lindsey Stirling, and Tim Ferriss use features I've built to connect with their fans. I'm currently geeking out about Svelte, mechanical keyboards, and minimalist UI design, and replaying Ocarina of Time.