[React] Class vs function component, which one should i be adapted?

It’s been a 2 month since i started to learn react.
When i learned React on FCC, I felt like Class component would be latest version compared with function component.
But whenever i struggle with come practical cases, i always found the solution with the hooks like useState, useEffect, useHistory.

Now i know how to convert the useState and useEffect to class component version but still consufing with the useHistory

import { useHistory } from "react-router-dom";

function HomeButton() {
  let history = useHistory();

  function handleClick() {
    history.push("/home");
  }

  return (
    <button type="button" onClick={handleClick}>
      Go home
    </button>
  );
}

And i realiezed that we cannot use this kinda hooks in class component.

  1. How do we use useHistory in class component?
  2. And Which one should i try to be adapted to use between class and functino component?

Function components are a somewhat recent feature of React, so a lot of “older” material does not cover them.

As far as I know you cannot use hooks like useHistory, useState, useEffect etc. in class components.
The good news is that you can use function and class components side by side. So if your component is not too complex the path of least resistance is to refactor it to a function component. If you decide to go this route the React Hooks FAQ has a good outline how to map class lifecycle functions to hooks

If your existing code base makes extensive use of the the class component lifecycle callbacks (componentDidMount, compontentShouldUpdate etc.) this migration might be too effort. In that case you can consider using an older version of react router, for example the docs for react router 3.x are all based on class components. That’s not a great solution as well, but might work temporarily.

The React docs also clearly state that classes are not going away so you shouldn’t rewrite all your code and forget about class components. I suggest you slowly adopt function components (and hooks) as you go.

No perfect solution, but I hope it helps anyways.

Cheers
Nemo

You can use the history object in a class component (props) and there is a HOC withRouter you can use as well (usage info, more examples).

1 Like