DEV Community

Ashutosh Sarangi
Ashutosh Sarangi

Posted on

2 1 1 1 1

React Hook in Class Component

Introduction

In some scenarios lets assume you have to, use React hook concept in react class based components.

But as you know react hooks only going to work in functional component if you wish to directly using them in class based component.

it will through an error.

So how to do it, there is a work around solution for the same.

There are 3 step solution

  1. Create a custom Hook, (You can directly use hook, but there you won't get more benefit)
  2. Use the hook in a Higher order component
  3. We need to wrap the Higher Order component in class based component.

Create a custom Hook

import {useState} from 'react';

const useGreet = () => {
  const [text, setText] = useState('');

//... do any additional operation / hooks you want to add

return text;   
}
Enter fullscreen mode Exit fullscreen mode

Creating a Higher Order Component

// import useGreet

export const MyHigherOrderComponentDemo = (Component) => {

  return (props) => {
    const text = useGreet();

    return <Component text={text} {...props}/>;
  }
}
Enter fullscreen mode Exit fullscreen mode

Wrap Higher Order Component in class based component

// import useGreet

class MyClass extends React.component {

render() {
   return (
    <p>{this.props.text}</p>
  )
}

}

export default MyHigherOrderComponentDemo(MyClass);
Enter fullscreen mode Exit fullscreen mode

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Cloudinary image

Video API: manage, encode, and optimize for any device, channel or network condition. Deliver branded video experiences in minutes and get deep engagement insights.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay