Table of contents
No headings in the article.
Syntax: Functional components are declared as functions, while class-based components are declared as classes.
State management: Class-based components can have state, which is managed through the
this.state
object and can be updated using thethis.setState()
method. Functional components can't have state, but can use theuseState()
hook to manage local state.Lifecycle methods: Class-based components have lifecycle methods such as
componentDidMount()
,componentDidUpdate()
, andcomponentWillUnmount()
, which can be used to execute code at specific points during the component's lifecycle. Functional components can use theuseEffect()
hook to achieve similar functionality.Performance: Functional components are generally faster than class-based components because they have less overhead and are easier for React to optimize.
Code clarity: Functional components are often more concise and easier to read than class-based components.
Default props: Class-based components can define default props using the
defaultProps
property, while functional components use thedefaultProps
argument.Refs: Class-based components can use the
createRef()
method to create a reference to a DOM element, while functional components can use theuseRef()
hook.Context: Class-based components can access context using the
this.context
property, while functional components can use theuseContext()
hook.Error handling: Class-based components can define an
errorBoundary
to catch errors in child components, while functional components can use theuseErrorHandler()
hook.Ex-
Functional Component:
import React from 'react'; function HelloWorld(props) { return ( <div> <h1>Hello, {props.name}!</h1> </div> ); } export default HelloWorld;
Class-based Component:
import React from 'react'; class HelloWorld extends Components { render() { return ( <div> <h1>Hello, {this.props.name}!</h1> </div> ); } } export default HelloWorld;
Both components render a simple "Hello, {name}!" message where
name
is a prop passed in from the parent component. The functional component is declared as a function that returns a React element, while the class-based component extendsReact.Component
and overrides therender()
method to return a React element.
Overall, functional components have become more popular in recent years because they are simpler, more concise, and easier to test. However, class components are still used in some cases, particularly when you need to manage complex state or use lifecycle methods that are not available in functional components.