What is the difference between functional and class components?
React supports two component styles. Modern React strongly prefers functional components with hooks; class components survive in legacy code.
Functional components — plain JavaScript functions that return JSX. State and lifecycle handled with hooks (
useState,useEffect). Less boilerplate, easier composition, smaller bundle.
Class components — ES6 classes extending
React.Componentwithrender()and lifecycle methods (componentDidMount,componentDidUpdate,componentWillUnmount). Usethis.stateandthis.setState.
Hooks unified the model — functional components can do everything class components could, plus easier reuse via custom hooks.
this binding gone — no more
this.method = this.method.bind(this)headaches.Code reuse — custom hooks beat HOCs and render props for sharing stateful logic.
Performance — equivalent in practice; functional components are slightly easier for the compiler to optimize.
New code — always functional + hooks. Class components only for maintaining legacy.
// Functional component (modern)
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `Count: ${count}`;
}, [count]);
return (
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
);
}
// Class component (legacy)
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
componentDidUpdate() {
document.title = `Count: ${this.state.count}`;
}
render() {
return (
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Count: {this.state.count}
</button>
);
}
}Both components do the same thing: display a counter that updates the document title. The functional version is shorter, has no constructor or render method, uses useState for state and useEffect for side effects.
The class version requires a constructor, this.state, this.setState, and the componentDidUpdate lifecycle method.
Always recommend functional components for new code. Know why: simpler syntax, hooks for logic reuse, closure-based prop capture.
Mention that class components are still valid but no longer recommended by the React team.