DEV Community


Posted on

Use hook functions in class component: React

Converting the legacy class components to functional components is not an easy task if the component is dealing with complex logic.

There are times when we can implement custom hook functions to achieve a shared functionality like triggering the popup with a message on any component. Eg: Popup will be visible on the component. But we can't consume the hook directly in a class based component. However there's a workaround to achieve it.

HOC with Hooks

Step 1:

Create a functional Higher Order Component which accepts the initialState for the hook and a react component as the param.

Step 2:

Import the hooks here and pass the hook functions as params to the return component.

Step 3:

Wrap the class component with our HOC component. Pass the initial states for the hook as params in the HOC.


Now we can call the hook methods from this.props.

Comments are welcomed!

Top comments (0)