Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use React hooks in React classic `class` component?

In this example, I have this react class:

class MyDiv extends React.component    constructor(){       this.state={sampleState:'hello world'}    }    render(){       return <div>{this.state.sampleState}    } } 

The question is if I can add React hooks to this. I understand that React-Hooks is alternative to React Class style. But if I wish to slowly migrate into React hooks, can I add useful hooks into Classes?

like image 710
Aminadav Glickshtein Avatar asked Nov 19 '18 09:11

Aminadav Glickshtein


People also ask

Can we use React hooks in class component?

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.

How do you use a hook inside a class component?

The only practical way to utilize hooks within class components is to mix the two types of components in a single tree. In theory, using hooks, you could use functional components to generate value and pass down that value through props to class components.

How do you use a hook in React component?

Instead, always use Hooks at the top level of your React function, before any early returns. By following this rule, you ensure that Hooks are called in the same order each time a component renders. That's what allows React to correctly preserve the state of Hooks between multiple useState and useEffect calls.

Can I use useEffect in class component?

useEffect can only be used in a React functional component. componentDidUpdate can only be called within a class component.


1 Answers

High order components are how we have been doing this type of thing until hooks came along. You can write a simple high order component wrapper for your hook.

function withMyHook(Component) {   return function WrappedComponent(props) {     const myHookValue = useMyHook();     return <Component {...props} myHookValue={myHookValue} />;   } } 

While this isn't truly using a hook directly from a class component, this will at least allow you to use the logic of your hook from a class component, without refactoring.

class MyComponent extends React.Component {   render(){     const myHookValue = this.props.myHookValue;     return <div>{myHookValue}</div>;   } }  export default withMyHook(MyComponent); 
like image 180
Joel Cox Avatar answered Sep 24 '22 21:09

Joel Cox