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.

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

While many AI coding tools operate as simple command-response systems, Qodo Gen 1.0 represents the next generation: autonomous, multi-step problem-solving agents that work alongside you.

Read full post

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️