React Components: Functional vs Class
React components are independent and reusable code blocks that return a React element. Functional Components and Class Components are two main types of components in React:
- Functional Components: They are basic functions that accept props as an argument and return JSX code instead of using a
Componentto work with functional components.
Functional components are also known as stateless components because they do not store state and they lack lifecycle methods and instances. Functional components can also be written as a single line with ES6:
Functional components are easier to write, read, understand, test and debug. They are mostly used to display content without any heavy logic, but they can be more complex if you want to use helper functions and React Hooks (version 16.8). Functional components should be favored until unless you need state and lifecycle methods, which are easily available to class components.
2. Class Components: In React, the components can also be declared as classes. As its name suggests, class components are created using the ES6 class syntax and they differ from functional components in several ways. First of all, class components need to be extended from a
Component class, which gives access to all the functions of the parent component. Second, they require a
render() method to return a React element (JSX code).
In addition to
render() method, we can add also Lifecycle methods inside class components. Class components are also known as stateful components because they take constructor function, where they can accept props and maintain their own data with state. Lastly, you can have access to props with
this.props because class components have instances.
In summary, functional components are concise and easier to understand and maintain. They are good options for simple components, but they lack certain features. On the other hand, class components implement logic and they are more complex than functional components by including state,
Component class, constructors, lifecycle and
render() methods. It is suggested to start with a functional component unless you need state and lifecycle methods because functional components can not perform these additions unless React Hooks is used.