Class Components to Functions

Convert class components to functions.

Let’s work with examples

Many examples for React components will be class-based instead of functional components and React hooks. There are four things in the code structure we’ll need to modify to convert from a class component to a functional component:

  1. The class declaration
  2. The class constructor
  3. Any component lifecycle functions
  4. The render() method

Class declaration

In the class declaration of the App component, we have the following code:

class App extends React.Component {

Here, we can change the class declaration to a simple Python def:

def App():

Class constructor

Next, we move on to the class constructor. We incorporate this into the code because this is usually where state variables are created and initialized. If a component doesn’t have a state that it’s managing, it may not have a constructor. The App component has five state variables to keep track of data that can affect the UI.

Get hands-on with 1400+ tech skills courses.