All Articles
Frontend7 min read7 November 2018

React Hooks: Rethinking How We Write Components

Dan Abramov announced React Hooks at ReactConf 2018. The room went quiet, then the Twitter responses started. Hooks changed how we write React components more profoundly than anything since the library launched.

ReactHooksFrontendJavaScript

The class component era of React had produced a pattern that worked but always felt slightly off. You split components into stateful classes and stateless functions. Stateful logic lived in lifecycle methods that were hard to test and hard to extract. Related code was split across componentDidMount, componentDidUpdate, and componentWillUnmount. Unrelated code was grouped together in the same lifecycle method. The render props and higher-order component patterns that had emerged to solve code reuse problems added nesting and indirection that made components hard to follow.

Dan Abramov's presentation of React Hooks at React Conf in October 2018 was one of those rare conference moments where you could feel the reaction in real time. The idea was to let function components have state and side effects, without class syntax, without lifecycle methods, without any of the patterns that made React components complicated.

The two core hooks were useState and useEffect. useState gave function components local state. useEffect replaced componentDidMount, componentDidUpdate, and componentWillUnmount. Together they covered the majority of what class components did, in code that was shorter and more direct.

The more interesting capability was custom hooks. Because hooks were just functions that called other hooks, you could extract stateful logic into reusable functions. The code reuse problem that render props and higher-order components had solved awkwardly was now solved cleanly. You could write a useWindowSize hook, a useFetch hook, a useLocalStorage hook, and compose them in any component that needed them.

The mental model shift was significant. Class components modelled components as objects with lifecycle. Hooks modelled components as functions that declared their dependencies and effects. The function model was easier to understand, easier to test, and easier to compose.

The Hooks RFC was published in October 2018, which meant the community had months to discuss, critique, and understand the proposal before it shipped in React 16.8 in February 2019. This preview period was unusual and valuable. It meant adoption started immediately after release because the community had been preparing.

The concerns about Hooks were real but turned out to be manageable. The rules of hooks (only call hooks at the top level, only call hooks from React functions) were unusual constraints that required linting tools to enforce. The closure behaviour of useEffect caught many developers initially. But these were learnable problems and the benefits outweighed the learning curve.

Found this useful?

Share it with someone who'd enjoy it.