ReactEasy

Why were Hooks introduced?

Hooks were introduced in React 16.8 (February 2019) to let function components have state and side effects, and to solve three problems with classes: stateful logic was hard to reuse without wrapper hell, related logic was split across lifecycle methods, and classes were confusing (this, binding) and harder to optimize.

The problems they solved

  1. Reusing stateful logic: before hooks, sharing logic meant higher-order components or render props, which nested components deeply ("wrapper hell") and obscured where props came from. Custom hooks share logic as plain functions.
  2. Complex components: subscribing in componentDidMount and unsubscribing in componentWillUnmount, with related updates in componentDidUpdate, scattered one concern across methods while mixing unrelated concerns in each. An effect keeps setup and cleanup together.
  3. Classes are hard for people and machines: this binding bugs, verbose syntax, and patterns that are hard to minify, hot-reload and compile ahead of time.

What came after

Hooks became the foundation for every later React feature:

  • Concurrent features (useTransition, useDeferredValue).
  • React 19's Actions (useActionState, useOptimistic, use).
  • React 19.2's useEffectEvent and <Activity>.
  • The React Compiler (1.0 in 2025), which analyzes function components and hooks to memoize automatically. It cannot optimize class components.

Compatibility

Hooks were added without breaking classes; both coexist. Most new code and libraries are hooks-only.

Code example

tsx
1// Before hooks: logic reuse via a higher-order component
2// const withWindowWidth = (Comp) => class extends React.Component {
3// state = { width: window.innerWidth };
4// onResize = () => this.setState({ width: window.innerWidth });
5// componentDidMount() { window.addEventListener("resize", this.onResize); }
6// componentWillUnmount() { window.removeEventListener("resize", this.onResize); }
7// render() { return <Comp {...this.props} width={this.state.width} />; }
8// };
9
10// With hooks: the same logic as a reusable function
11import { useEffect, useState } from "react";
12
13export function useWindowWidth() {
14 const [width, setWidth] = useState(() => window.innerWidth);
15 useEffect(() => {
16 const onResize = () => setWidth(window.innerWidth);
17 window.addEventListener("resize", onResize);
18 return () => window.removeEventListener("resize", onResize); // setup + cleanup together
19 }, []);
20 return width;
21}
22
23export function Banner() {
24 const width = useWindowWidth();
25 return <p>{width < 640 ? "Mobile layout" : "Desktop layout"}</p>;
26}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app