How to use Hooks in React classes

Let's suppose that we have a classic class component 'OldComponent.js' in React:

jsx

import React, { Component } from 'react';

class OldComponent extends Component {
    
  render() {        
    return (
      <div className = 'Old'>
        <p>👋 Hello, I am an old React component.</p>
      </div>
    );
  }
}

export default OldComponent;

Now, let's suppose that we create a new Hook in 'NewComponent.js':

jsx
import React, {useState} from 'react';

const useHook = () => {
    
    const [clicks, setClicks] = useState(0);
    
    return <button onClick = { () => setClicks(clicks + 1) }>
                {clicks} times clicked 😼
           </button>;
}

export default useHook;

First approach would be to integrate this Hook in the old component like this (wrong solution):

jsx

import React, { Component } from 'react';
import useHook from './NewComponent.js';

class OldComponent extends Component {
    
  render() {        
    
    // 🔴 This returns an error. Unsing Hooks into classes is not allowed.
    var newButton = useHook();
  
    return (
      <div className = 'Old'>
        <p>👋 Hello, I am an old React component.</p>
        {newButton}
      </div>
    );
  }
}

export default OldComponent;

Then, the solution is to place the Hook outside the class. We can place it in 'OldComponent.js' but declaring it like this:

jsx

import React, { Component } from 'react';
import useHook from './NewComponent.js';


// ✅ Calling the Hook outside the class
const NewButton = () => {
    
    var button;
    
    button = useHook();
    
    return button;
}

// ✅ Declaring the new button as a component
class OldComponent extends Component {
    
  render() {        
  
    return (
      <div className = 'Old'>
        <p>👋 Hello, I am an old React component.</p>
        <NewButton></NewButton>
      </div>
    );
  }
}

export default OldComponent;

Mixing old classes and new React Hooks, doesn't require code rewriting.

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.