JS Guide
HomeQuestionsSearchResources
Search

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsreact
PrevNext
react
junior
components

What is the difference between functional and class components in React?

components
functional-components
class-components
hooks
Quick Answer

Functional components are JavaScript functions that return JSX and use hooks for state/lifecycle. Class components extend React.Component and use this.state and lifecycle methods. Functional components with hooks are now the recommended approach.

Detailed Explanation

Functional Components:

  • Plain JavaScript functions returning JSX
  • Use hooks (useState, useEffect, etc.) for state and side effects
  • Simpler, less boilerplate
  • Easier to test and reason about
  • Better performance (slightly)
  • Recommended for new code

Class Components:

  • ES6 classes extending React.Component
  • Use this.state and this.setState() for state
  • Lifecycle methods (componentDidMount, etc.)
  • Required 'this' binding for methods
  • Still supported but considered legacy

Why Functional Components Won:

  • Hooks provide all class component features
  • More concise code
  • Easier to share stateful logic (custom hooks)
  • No 'this' binding confusion

Code Examples

Functional component with hooks
import { useState, useEffect } from 'react';

function Counter({ initialCount = 0 }) {
  // State hook
  const [count, setCount] = useState(initialCount);
  
  // Effect hook (like componentDidMount + componentDidUpdate)
  useEffect(() => {
    document.title = `Count: ${count}`;
    
    // Cleanup (like componentWillUnmount)
    return () => {
      document.title = 'React App';
    };
  }, [count]); // Dependency array
  
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>+</button>
      <button onClick={() => setCount(count - 1)}>-</button>
    </div>
  );
}

Resources

React Docs - Your First Component

docs

React Docs - State: A Component's Memory

docs

Related Questions

Explain the useState and useEffect hooks and their common patterns.

mid
hooks

What are props in React and how do you pass data between components?

junior
props
Previous
What is JSX and why does React use it?
Next
What are props in React and how do you pass data between components?