devlog

主に web 開発とかプログラミングについて書きます

【翻訳】コードを綺麗にするためにCustom Hooks を書こう

前回の続きで英語勉強の翻訳2回目。 がんばりまっちゅん。といいつつ今回の釣り画像はmodel pressさんの斎藤飛鳥さん。 やばいくらい透明感がやばい。(日本語彙力は死んでいる)

今回から英語の本文と日本語の翻訳を交互の載せる

https://img-mdpr.freetls.fastly.net/article/739B/nm/739BeYfAdQoP9TWNlHR94KYMLiewaqjWXyZmJlglhcg.jpg?width=700&disable=upscale&auto=webp

(画像4/8) 齋藤飛鳥、本音を赤裸々告白 “本当の姿”見せる

前回の翻訳記事

nkgr.hatenablog.com

ちなみに前回の翻訳記事を社内で持ち寄ってレビューし合おうって言ったが、1時間で3人全員分の記事をレビューできなかった。

結局、翻訳中の不明点を相談しあう場所にするのが良さそう。という結論になった。

あと社内で翻訳の話したら便利なChrome拡張教えてもらった。マジ感謝。

chrome.google.com

今週の元ネタ

daveceddia.com

ここから翻訳記事

React hooks make it easy to add a single piece of state to a component. But it’s also a breeze to write your very own custom hooks, just by moving the hooks-related code into a function.

React hooks を使うことで簡単に component に 単一の stateを追加することができる。 しかし hooks に関連するコードを関数の中に移動することで、カスタム hooks を書くこともできます。

Say you need a boolean true/false flag to keep track of whether a bit of spoiler text is shown or hidden. You could wire it up like this…

ネタバレの一部の表示非表示を追跡するための true / false の真偽値フラグが必要だとします。こんな風にかけます...

import React, { useState } from 'react';

function SpoilerAlert({ spoilerText }) {
  const [isVisible, setVisible] = useState(false);

  return (
    <div>
      <button onClick={() => setVisible(!isVisible)}>
        {isVisible ? 'Hide' : 'Show'}
      </button>
      {isVisible && <span>{spoilerText}</span>
    </div>
  );
}

The useState here doesn’t do a great job of expressing the intent of that state though. Don’t get me wrong – I’m not saying it’s bad, just that I think it could be better. Wouldn’t it be cool if it looked like this instead?

ここの useState は 状態管理を意とする表現としてはふさわしい仕事をしていない。誤解しないでください。私はわすりとは言っていません。ただもっとよくすることができると思っています。代わりにこんな風にすることでよいと思いませんか?

import React, { useState } from 'react';

function SpoilerAlert({ spoilerText }) {
  // useToggle doesn't exist yet, but what if it did?
  const [isVisible, toggleVisible] = useToggle(false);

  return (
    <div>
      <button onClick={toggleVisible}>
        {isVisible ? 'Hide' : 'Show'}
      </button>
      {isVisible && <span>{spoilerText}</span>
    </div>
  );
}

It’s a small change, but it reads more nicely. The onClick={toggleVisible} prop, especially, is more succinct and clear than onClick={() => setVisible(!isVisible)}.

これは小さな変更です。しかしうまく読めます。 特にonClick={toggleVisible} props はonClick={() => setVisible(!isVisible)} よりも簡潔かつ明快 です。

Let’s write the useToggle hook.

では、useToggle hook を書きましょう

Custom Hooks are Just Regular Functions - Custom Hooks は ただの習慣的な関数です

You can bundle up any chunk of hooks logic into a function to make your very own fancy custom hook! Just make sure your function name starts with “use”.

独自のカスタムhooksを作ることで、hooks のロジックのかたまりを 関数にまとめることができます。単に 関数名を"use"から始まることを確認してください。

Once you see how easy is is to write a custom hook, I think you’ll start to see uses for them all over your app.

一度カスタムフックを書くのがどんなに簡単かを一度みてください。あなたのアプリ全てで利用可能かを見始めるでしょう。

Our useToggle hook is mostly just a call to useState, but instead of handing back a general-purpose “setter” function, we’re gonna create a purpose-built “toggler” function and return that instead.

useToggle hook は ほとんど useState を呼んでいるだけです。しかし 一般的な目的の"setter" 関数の返す代わりに、特別に作った"toggle" 作成し代わりに返却します。

We’re wrapping up the setter logic to make it crystal clear to whoever uses this hook that the value is meant to be toggled.

このhook は トグルを意図している値 であるということを明確するために、setter logic をラップしています。

function useToggle(initialValue) {
  const [value, setValue] = useState(initialValue);

  const toggleValue = () => setValue(!value);

  return [value, toggleValue];
}

I think of little hooks like this as “quality of life” hooks. Did we desperately need to create this hook? Was the code really that bad before? No. It was fine. But this little bundle of 5 lines of code makes it finer.

私は "quality of life" hooks のような ものだと考えている。必ずこのhook を作る必要がある?前のコードは本当は悪かった?いいえ。よかった。しかし、この5行のコードはよりよくしたと言える。

Keep custom hooks like this in a file (say, hooks.js?), and next time you need to create a toggleable value, just import { useToggle } from './hooks' and you’re good to go!

このような カスタム hooks は 単一のファイルに保存して(hooks.js と呼ぶ)、次回トグルが可能な値を作る必要がある場合は、単に import { useToggle } from './hooks' するだけでよいです!

Another Example: useBoolean - 別の例:useBoolean

Just to hammer the point home, let’s see one more simple custom hook – another variant on a boolean value.

家に帰るだけ、真偽値を扱う簡単な別の形のhookをお見せしましょう

This one is meant for a value you need to explicitly turn ON and OFF, instead of toggle. Imagine a modal dialog with only one way to open it, and a few ways to close it (X button, Escape key, Cancel button, after a request succeeds, …).

これは、トグルの代わりに、明確にON と OFFを切り替える必要がある値を意図しています。唯一の方法で開き複数の方法でそれを閉じるモーダルダイアログを想像してください。(X ボタン、esc キー、キャンセルボタン、リクエストが成功したあと...)

You might initially rely on useState to create a boolean:

booleanの useState を最初にあてにするかもしれない。

const [isVisible, setVisible] = useState(initialValue);

Then you could define a couple helpers, and pass one of these wherever you need a callback function (like for an onClick handler or similar).

次に対になるヘルパーを定義し、コールバック関数が必要なところに、これらのうちの一つを渡すことができます。(onClick ハンドラーなど)

const showModal = () => setVisible(true);
const hideModal = () => setVisible(false);

I’d say a function called showModal is clearer than () => setVisible(true). But we can go one step further, and bundle that logic into a custom hook:

showModal が呼ばれる関数のほうが、 () => setVibible(true) よりも明快です。しかし、もう1ステップ進んで、カスタムhook の中にロジックをまとめましょう。

function useBoolean(initialValue) {
  const [value, setValue] = useState(initialValue);

  const setTrue = () => setValue(true);
  const setFalse = () => setValue(false);

  return [value, setTrue, setFalse];
}

Again it’s all about making the intent clear, and tidying up the code a bit. All we’ve done is move the state and the helper callbacks into a new function, and now we can use it in a component like this:

繰り返しますが、これは意図を明確にし、コードを少し整理することでう。stateとヘルパーコールバックを新しい関数の中に移動すれば完成です。そしてコンポーネントの中でこのように使えばよいです。

const [isVisible, showModal, hideModal] = useBoolean(initialValue);

Now you have a reusable bit of state and helper functions! The next time you need a flag to show/hide a sidebar, a tooltip, or whatever else, just import useBoolean.

再利用可能な stateとヘルパー関数を手に入れました。あなたが次回、サイドバーやツールチップなどを表示非表示するフラグが必要な時に、単に useBoolean を importします。

Look for little opportunities to create custom hooks in your own code. How can you make your existing code more expressive?

あなたのコードの中で、カスタム hook を作る機会を探してください。あなたのコードの価値が高くなりますよ!!

かなり翻訳が怪しい箇所と不明点

But it’s also a breeze to write your very own custom hooks, just by moving the hooks-related code into a function.

a breeze to の意味が難しい

Custom Hooks are Just Regular Functions

Regular をどう訳すか

You can bundle up any chunk of hooks logic into a function to make your very own fancy custom hook! Just make sure your function name starts with “use”.

fancy is なに?

I think you’ll start to see uses for them all over your app.

start to see uses の意図 が難しい

handling back

返す?くらいの意味

Just to hammer the point home

家に帰るだけ... 意味不明。

所感

  • 所用時間 4ポモドーロ
  • 前回より早くなった気がする
  • 結構微妙な比喩表現が辛い。無視した箇所もある。
  • 飛鳥ちゃんはやばいくらい透明感がやばい。