Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoke a React custom hook inside the class component

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

like image 407
yasarui Avatar asked Jun 25 '26 01:06

yasarui


1 Answers

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.

like image 161
Son Nguyen Avatar answered Jun 26 '26 16:06

Son Nguyen