In this tutorial, you will learn how to convert a class component written using react into a functional component. Historically, functional components had a bad press. Functional components used to be less performant than class components. Functional components also provided no life-cycle methods.
As react has evolved, functional components perform the same as their class components. Using hooks/react context you can now add life-cycle methods to functional components. This allows you to do cool things like manage state. I once failed a job interview coding challenge because I used a class component. People love functional components!
Converting a class component into a functional component. First, let's start with a simple 'PureComponent':
Class components have a slight overhead to set-up, just to render a single prop. You need to remember to inherit correctly, you need to a constructor to initialize default state, you need to use a life-cycle method to update values. It all feels kind of long-winded. The same functionally can be done within a functional component using a lot less code:
In a functional component, we can use 'useState' to add a property to state. The value you pass into
useStateis the default value the property will be set with. useState will return to things. The property and a function that updates the property.
As a functional component has no life-cycle methods, in order to replicate the same type of functionality as 'componentDidMount', we can use 'useEffect'. componentDidMount() for anyone new to react is a life-cycle function that gets called after c omponent is rendered.
If you try to use 'useEffect' incorrectly you will bump into a re-render too many times issue. This type of error is the same error you would encounter if you tried to update state within the render method of a class component. To fix the issue you need to ensure you pass at a minimum an empty array at the end, like so:
Adding the empty array means useEffect will never update. The empty array is value to use but react will produces a warning. Armed with 'useState' and 'useEffect', you can now replicate all the life-cycle goodness that a class component provides. Using a lot less code as well! Enjoy!