React gives us two ways to write our components — functional components and class components. In this blog, I’ll try to explain the differences between them, and the pros and cons of each.
First, what is a React component?
React components are a way to transform a piece of UI into a piece of code that can be reused. A component is like a function that takes input (called by props) and returns a React element that describes what should be displayed in the DOM.
Differences in syntax
Let’s take a look at the syntax of functional components and class components-how to write each component style, different ways to use React state, and how to write lifecycle methods.
Now take a look at the same component as a class component. It’s just an ES6 class that has a render method that returns JSX for rendering.
In React, state refers to an object within a component that is used to store the values of properties owned by that component. When this state object changes, the component is redrawn.
State in functional components:
In the functional component, we can use the useState hook to initialize the state. If you’re unfamiliar with React Hooks, I recommend taking a look at the documentation here.
In the example below, we’ve added state to our Profile example, where state is held by one bio property.
useState takes the initial value of the state property and returns:
- bio — current state
- setBio is a setter function that updates state
In a class component, the state object is initialized in the constructor and can be used anywhere in the component using this.state.propertyName. In the example below, we have added the state again with bio to our Profile example functional component. We render this in the render method using this.state.bio.
We looked at both functional and class components and saw the differences between them. Both have their pros and cons, however functional components are becoming more popular for several reasons:
- In the past, functional components were limited because you could not use methods or lifecycle state. Since hooks were added into React, you can achieve anything using a functional component, that you can do with a class component.
- The React team mentioned that it is possible to optimize the performance of functional components in the future.
- Functional components are often cleaner and more concise, resulting in more readable and testable code.