How to move from class component to function component

Swathi Bhat
2 min readFeb 7, 2022

--

In the last post, I have talked about the differences between a class component and a functional component. This post is about how a component can be moved from a class to a functional component.

Consider a class component that gets a set of To-Do items from the server and lets the user create a new item. Basically, a To-Do-List component. When using the class component it would be written as follows:

Class Component ToDoList

In the above example, the component mounts and gets the list of tasks from the server on mount (componentDidMount lifecycle function). The list of items are then set to the state and then displayed. For every addition to the list, the item is sent to the server and added to the state (postTask function).

Now, we convert the above component to a function component. First, move the state. React provides the useState hook for this purpose. This returns an array with the value and its setter function. So the state in the constructor becomes,

Next, move the fetch in componentDidMount function. The useEffect hook provided serves the purpose. The hook takes 2 values: function to be executed when the component mounts and the values to look for. When the values provided changes, the function is executed. This becomes,

The render function is replaced with a simple return. The function returns the JSX component to be displayed. In conclusion, the final functional component looks like this:

Functional toDoList component

As you can notice, the functional component is much more readable and easier to understand when compared to the class-component. The functional component is much more developer friendly, hence, much more popular these days.

--

--

Swathi Bhat
Swathi Bhat

Written by Swathi Bhat

A software developer based out of Bangalore, who loves to talk about JavaScript!

No responses yet