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.
Functional Components:
Class Components:
Why Functional Components Won:
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>
);
}