- World-Wide-Web Codes:
- The roadmap to learn React
- React Components
- React Virtual DOM
- React Lifecycle
- React State
- React Props
- React Render
- React JSX
- React Functional Component vs Class Component
- React Function Component Props
- React Function Component:State
- React Arrow Function Component
- React Stateless Function Component
- React Pure Component
- React Function Component: Export & Import
- React Controlled vs Uncontrolled
- React Hooks
- React HOC
- React + Redux
Understanding Functional Components vs. Class Components in ReactIn the world of React, there are two ways of writing a React component. One uses a function and the other uses a class. Recently functional components are becoming more and more popular, so why is that?
Differences between functional and class-Components
The most obvious one difference is the syntax.
A class component requires you to extend from React.Component and create a render function which returns a React element.
This requires more code but will also give you some benefits.
Let's start with a simple example of a Functional Component in React defined as FunctionalComponent which returns JSX:
As you can see, a functional component is a function that returns JSX. If you are not familiar with arrow functions introduced in ES6, you can also check out the example below without.
On the other hand, when defining a class component, you have to make a class that extends React.Component. The JSX to render will be returned inside the render method.
Below is the same example but without using destructuring. If you are not familiar with destructuring, you can learn more about destructuring and arrow functions introduced in ES6!
See render with class component in CodePen
Passing propsPassing props can be confusing, but let's see how they are written in both class and functional components. Let's say we are passing props of the name "Jama" like below.
Inside a functional component, we are passing props as an argument of the function. Note that we are using destructuring here. Alternatively, we can write it without as well.
In this case, you have to use props.name instead of name.
See props with functional component in CodePen
Since it is a class, you need to use this to refer to props. And of course, we can use destructuring to get name inside props while utilizing class-based components. See props with class component in CodePen
Handling state in functional components
See state with functional component in CodePen
Handling state in class components
See state with class component in Codepen
See lifecycle with functional component in Codepen
See life cycle with class component in Codepen
The key distinction between the two is that class components have state and lifecycle method while function component do not, As long as you do not need state or lifecycle method, use a function component.