Functional vs Class Components
Definition
Functional components are simple JavaScript functions that accept props and return JSX. Class components are ES6 classes that extend React.Component and require a render() method.
Explain Like I'm New
Imagine building a chair. A Class component is like a complex factory assembly line with a manual you have to read (constructors, 'this' keyword, lifecycle methods). A Functional component is like a simple 3D printer: you give it a design (props), and it prints the chair (JSX). Before 2019, only the factory (Class) could remember things (State). Now, thanks to Hooks, the 3D printer can do everything the factory can do, but with way less headache.
Real World Example
If you look at an old 2017 React codebase, you will see `class App extends React.Component`. You will see `this.state = {}` and `this.handleClick.bind(this)`. In modern React, you will exclusively see `function App()` and `const [state, setState] = useState()`.
Common Use Cases
- •Functional Components: The modern standard for building 99% of all React UI.
- •Class Components: Maintaining legacy codebases, or specifically building an Error Boundary (which currently requires a Class).
Interactive Example
import React, { useState } from 'react'; // --- MODERN FUNCTIONAL COMPONENT --- // Simple, readable, no 'this' keyword. export default function ModernCounter() { const [count, setCount] = useState(0); return ( <div className="p-4 border rounded mb-4"> <h2>Functional Component</h2> <p>Count: {count}</p> <button onClick={() => setCount(c => c + 1)}>Increment</button> </div> ); } // --- LEGACY CLASS COMPONENT --- // Verbose, requires constructor, 'this', and manual binding (if not using arrow functions) export class LegacyCounter extends React.Component { constructor(props) { super(props); this.state = { count: 0 }; // We used to have to do this: this.handleClick = this.handleClick.bind(this); } handleClick = () => { this.setState({ count: this.state.count + 1 }); } render() { return ( <div className="p-4 border rounded"> <h2>Class Component</h2> {/* Notice how we have to use 'this' everywhere */} <p>Count: {this.state.count}</p> <button onClick={this.handleClick}>Increment</button> </div> ); } }
Interview Questions
basic
- What is the main difference between Functional and Class components?
- Can you use Hooks (like `useState`) inside a Class Component?
intermediate
- Why did React shift away from Class components?
- What is the `this` keyword, and why did it cause problems in Class components?
advanced
- How do Functional components handle the concept of `componentDidMount` compared to Class components?
- What is a 'PureComponent' and how do you achieve the same thing with Functional components?
trick
- Are Functional components actually faster/more performant than Class components?