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.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

đź‘‹ Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay