DEV Community

Tamb
Tamb

Posted on

Getting Weird: "Hooks" in React Class Components

Before we begin. I know: Class Components are toast. They're dead and they ain't coming back. I'm just messing around in this post... so let's get weird.

We're going to create a contrived example of two components that will fetch the same data. The "hook" created will be a fetch call that exposes data to state.

Here's the Codesandbox: click me!

The "Hook"

export async function useTodos() {
  this.setState({
    fetching: true,
  });

  const resp = await fetch("https://jsonplaceholder.typicode.com/todos");
  const data = await resp.json();
  this.setState({
    todos: data,
    todoCount: data.length,
  });
}
Enter fullscreen mode Exit fullscreen mode

The above code simply fetches data and assigns it to state. this is nebulous at this point. It will refer to the housing function. But we'll assign the context of this in the next code snippet.

Component 1

import React from "react";
import { useTodos } from "./hooks";

export default class TodoCounter extends React.Component {
  constructor(props) {
    super(props);
  }

  UNSAFE_componentWillMount(): void {
    useTodos.call(this);
  }

  render() {
    return (
      <div>
        <p>Todos: {this.state?.todoCount}</p>
      </div>
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

Here we are assigning the value of this in the hook by using call in the component.

Note how you don't even have to define state here to access the hook data.

And (like hooks) you can use this in other components

import React from "react";
import { useTodos } from "./hooks";

export default class TodoList extends React.Component {
  constructor(props) {
    super(props);
  }

  UNSAFE_componentWillMount(): void {
    useTodos.call(this);
  }

  render() {
    return (
      <ol>
        {this.state.todos?.map((todo, i) => {
          return <li key={i}>{todo.title}</li>;
        })}
      </ol>
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

So yeah, it's super stupid. But you could use "hooks" all along with class components. We got weird.


Side note: I hate functional components. I think the lifecycle methods of class components map more closely to how DOM and web component lifecycles work. But React is ditching all of that for their functional approach. That's fine. But I'm just switching over to StencilJS instead. I prefer my OOP.

Top comments (0)