HomeREACT JSDifference between Functional and Class components?

Difference between Functional and Class components?

Here’s a clear breakdown of the difference between Functional and Class components in React 👇


1. Definition

Functional Component
A simple JavaScript function that takes props as input and returns JSX.

function Greeting(props) {
  return <h1>Hello, {props.name}</h1>;
}

Class Component
A JavaScript class that extends React.Component and uses a render() method to return JSX.

class Greeting extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

2. Syntax Simplicity

  • Functional: Short and clean, easier to read and write.
  • Class: Verbose, requires render() method and this keyword.

3. State Management

  • Functional: Uses React Hooks (useState, useReducer) for state.
  • Class: Uses this.state and this.setState().

4. Lifecycle Methods

  • Functional: Uses Hooks (useEffect, useLayoutEffect) instead of lifecycle methods.
  • Class: Has lifecycle methods like
    • componentDidMount()
    • componentDidUpdate()
    • componentWillUnmount()

5. Performance

  • Functional: Initially faster (lightweight). With Hooks, they can manage state and side effects effectively.
  • Class: Slightly heavier due to more boilerplate, but performance is now nearly the same.

6. this Keyword

  • Functional: No this keyword, props are directly accessible.
  • Class: Requires this.props and this.state.

7. Popularity / Best Practice

  • Functional: Modern standard in React (preferred for new projects).
  • Class: Considered legacy but still widely used in older codebases.

Summary Table

FeatureFunctional ComponentClass Component
SyntaxSimple functionES6 class
StateHooks (useState)this.state
LifecycleHooks (useEffect)Lifecycle methods
this keywordNot usedUsed
PerformanceLightweightSlightly heavier
Modern usagePreferred (React 16.8+)Legacy

Share: 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *