Switching React Class Components to Functional Components using Hooks
Now that my final project is functioning and completed, I decided to take on the task of switching my class components to functional components using React Hooks to keep up with the latest technology.
First, I will start by changing the name of the component from:
class PostsList extends Component
to
function PostsList(props)
This allows me to remove the “Component” part from import, since it is not longer needed and change it to useState, which is a hook allowing us to use local state in our functional component.
import React, { useState } from 'react';
State is now set using the following syntax:
const [sortClicked, toggleSortClicked] = useState(false)
What’s happening here is “array destructuring”. Since useState returns an array with two items, sortClicked is set to the first item (the current value) and toggleSortClicked is set to the second item (the function that allows the state to update). The argument for useState is the initial state.
Once useState is set up, all of the “setState” functions must be removed. State is now updated by using the “toggleSortClicked” function. Since we are toggling between true and false, setting the state would look like this:
toggleSortClicked(!sortClicked)
Because lifecycle methods can only be used in class components, these will need to be removed (i.e. render and componentDidMount). Instead of componentDidMount, we will use a React hook called useEffect (which also needs to be imported along with useState). This hook, useEffect, acts like componentDidMount and componentDidUpdate combined.
useEffect(() => { props.fetchPosts()}, [])
useEffect takes two arguements, the first is the code you would like executed, and the second is when you would like it to occur. If you omit the second argument, it will update every time a component re-renders. However, if you have the second argument as an empty array, it will only run when the component mounts. Additionally, you can customize the second argument to run only when a certain part of the component updates.
Finally, all references to “this” will need to be removed since it is no longer a class component. Once all these steps are completed, we have successfully changed a class component to a functional component using React hooks!