Hooked on Hooks

This is the English version of this article.

この記事の日本語版はこちらです。

At last year’s React conference, hooks were introduced as a new way to write React components. Here’s what a React component using the state hook looks like:

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

In short, a component is no longer a class, but rather a function that outputs the next state. Thinking of components as state transition functions is, in my opinion, an important simplification for reasoning about UI.

For larger components, hooks also have the effect of concentrating all related code into one place. You can visually observe the change with the following GIF. Related parts of the component have the same color:

Hooks are not limited to React. There’s already a solid Flutter implementation, and Vue 3 will supposedly be released with a version of hooks as well.

If you’re looking for more sane ways to architect your component-based frontend, it’s definitely worth your time to take a look at React Hooks and what they offer.