8

I am able to see a lot of threads explaining how to use a custom hook inside a class component using a higher-order component, In that case, we are using a Hooks output value inside the class component.

Is there any way we can invoke a hook inside the class component while using HOC? because sometimes the hooks are accepting some parameters. and the parameters for that function are based on the state of a class component

Accessing the hook value inside the class component

import React from 'react';
import { withSampleHookHoc } from './withSampleHookHoc';
    
class SampleClassComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
          name: 'Guest',
        };
    }
    render() {
        return <h1> Sample Class Component - {this.props.name} </h1>;
    }
}
    
export default withSampleHookHoc(SampleClassComponent);

But what I want to have is passing the state value as a parameter to the hook and invoking it from the class component

import React from 'react';
import { withSampleHookHoc } from './withSampleHookHoc';

class SampleClassComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
          text: 'Guest',
        };
    }
    render() {
        return <h1> Sample Class Component - {this.props.name(this.state.text)} </h1>;
    }
}
    
export default withSampleHookHoc(SampleClassComponent);

Code URL

2 Answers 2

4
+50

Yes you certainly can. Stackblitz example here: https://stackblitz.com/edit/react-bgum6q?file=src/Components/SampleClassComponent.js. Edit the input then click the Update name button to see it works.

Essentially, you just return some function from your hook, which will be passed to the class component as a prop via the HOC. Then, you have access to this function inside your class component and can do whatever you like.

If you have any questions, just add a comment to this answer.

Sign up to request clarification or add additional context in comments.

Comments

4

From the React Hooks FAQ:

You can’t use Hooks inside a class component, but you can definitely mix classes and function components with Hooks in a single tree. Whether a component is a class or a function that uses Hooks is an implementation detail of that component. In the longer term, we expect Hooks to be the primary way people write React components.

In other words, you can create a functional component that takes in your class' state values as props, calls a hook using those values, and renders some output.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.