DEV Community

Dani Akash ๐Ÿงช๐Ÿ’ฅ
Dani Akash ๐Ÿงช๐Ÿ’ฅ

Posted on

I recreated React's class component lifecycle methods with hooks

Project - lifecycle-hooks, also available in npm

I recently started working on an old react native project where I had to upgrade react-navigation from v3 to v5.

To take advantage of the new navigation hooks in version 5, I had to migrate existing class components to react hooks.

At first, it seemed like a straight forward case of refactoring some bit of code. However, I quickly realized how difficult the task at hand is...

Class component to hooks conversion is just not straight forward. Hooks are awesome when you are building new components but they are definitely not created with migrating class components in mind.

As react documentation says, class components aren't going away, so you probably won't have to migrate your project to functional components in most cases.

But if you run into a situation like me where you need the powerful hooks from react-navigation, react-spring or any other similar library, lifecycle-hooks will make your migration a lot easier.

traditional class state

// Initialization
this.state = {
  name: "",
  email: "",
};

// updating name
this.setState({
  name: "John Doe",
});

lifecycle-hook's useState

import { useState } from "@daniakash/lifecycle-hooks"

// Initialization
const [state, setState] = useState({
  name: "",
  email: "",
});

// updating name
setState({
  name: "John Doe",
});

Likewise, I have also created hooks for componentDidMount, componentDidUpdate & componentWillUnmount which will let you quickly move code without having to worry about dependency arrays of useEffect

You can try these hooks in the following codesandbox playground. Let me know your thoughts! Feedbacks & PRs welcome โœจ

Top comments (0)