atulr.com/blog
atulr.comtwittergithublinkedin

⚛️ Using React hooks for functional components with perfect fallback for class components.

June 12, 2019

This would be a very short post (approx 2min read). I recently wanted to abstract away a functionality that we had to use for multiple React components. I decided that I will write it using React hooks. Only issue is that we had a lot of legacy class components that needed the same functionality. So that would mean:

  1. Rewrite all components to functional components - Big NO NO
  2. Duplicate the same logic in both hooks and hoc format. But what do we say to code duplication? Not today!

After tinkering around a bit I came up with the following hack that allows me to write my logic as a hook and have great fallback option for class components in the form of a HOC.

We will take a simple example for this post. Lets say we have a hook as follows:

import React, { useState } from 'react'

// Hook for functional components
export const useCountry = () => {
  const [country] = useState('IN')
  return country
}

Now to make it work with a class components let add a HOC that uses this hook.

import React, { useState } from 'react'

// Hook for functional components
export const useCountry = () => {
  const [country] = useState('IN')
  return country
}

// HOC for class components
export const withCountry = Component => {
  return props => {
    const country = useCountry()
    return <Component {...props} country={country} />
  }
}

Usage:

For a functional component you could do:

const MyComponent = props => {
  const country = useCountry()
  return (
    <div>
      <div> Hi, I am from </div>
      <div>{country}</div>
    </div>
  )
}
export default MyComponent

And for a class component you would do:

class MyComponent extends React.Component {
  render() {
    const { country } = this.props
    return (
      <div>
        <div> Hi, I am from </div>
        <div>{country}</div>
      </div>
    )
  }
}

export default withCountry(MyComponent)

This simple trick allows you to use the same hook with class components (as a HOC 🤨)

Hope this helps 🎉

Like what you read? ❤
Please do let me know by commenting below. If you feel like treating, you can also buy me a coffee ;)

Atul RWritten by Atul R a developer 🖥, author 📖 and trainer 👨🏽‍🎓. He primarily works on Javascript ecosystem and occasionally hacks around in C++, Rust and Python. He is an open source enthusiast and making useful tools for humans. You should follow him on Twitter