DEV Community

Richard Oliver Bray
Richard Oliver Bray

Posted on

How to use hooks in React Class components

You're probably thinking, why on earth would anyone want to use a hook in a class based component, two words, legacy projects.

Hooks are cool and so are functional components, but if you're working on a 4 year old project that has loads of class-based components, you don't have the time to convert them to function based components. What's more, loads of newer libraries only use hooks.

So if you want to keep a legacy project up-to-date, this is a really helpful technique.

The code

import { Component } from 'react';
import { useNavigate } from 'react-router-dom';

class Login extends Component {
  render() {
    return (
      <>
        <p>My awesome component</p>
        <button type="button" onClick={() => this.#handleClick()}>
          Click here
        </button>
      </>
    );
  }

  #handleClick() {
    this.props.navigate('/dashboard');
  }
}

function addHookTo(Component) {
  function CompWithHook(props) {
    const navigate = useNavigate();

    return <Component {...props} navigate={navigate} />;
  }

  return CompWithHook;
}

export default addHookTo(Login);
Enter fullscreen mode Exit fullscreen mode

Aaaaand that's it!

Credit where credit is due

I could take all the credit and say my clever mind figured all this out but I actually saw it on the React Router website here -> https://reactrouter.com/docs/en/v6/faq#what-happened-to-withrouter-i-need-it

They have a good example on there of adding multiple hooks.

Anyway, I hope you found this useful.

Top comments (0)