reactjs / reactjs/react.dev

assigning a function to a `useState` variable

オープン
#3,297 コメント 0 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

主要言語
JavaScript
スター
11.8k
フォーク
7.9k
平均マージ
1日 11時間
マージ済み PR(30日)
11

説明

I was toying with storing a function in a useState variable, like this:

const behavior = () => {
  // set something up
  return () => {
    // tear it back down
  }
}

// inside the component
const [cleanupFunction, setCleanupFunction] = useState(null)

useEffect(() => {
  if (behavior){
    const cleanup = behavior()
    setCleanupFunction( () => cleanup )
  } else {
    cleanupFunction && cleanupFunction()
  }
}, [behavior])

This pattern is great for when you want to set up and tear down behavior when a prop changes, rather than wait until unmount. You can imagine that different behaviors with their associated cleanups can be passed in.

I was initially tempted to say setCleanupFunction(cleaup), but this was not working - my function was being called without me explicitly calling it. This explanation on stackoverflow gives a crucial tidbit: when storing a callback as a useState variable, it must be stored as a callback function which returns the function you want to call. I feel this use case should be somewhere in the react docs in the hooks section.

Thank you for everything you do!

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

まず、useState と useEffect に関連する React Hooks ドキュメントのセクションを見つけます。issue に示されている動作を文書化します。state に関数を保存するには、その関数を返す updater callback が必要であること、および setup と cleanup のユースケースを説明します。適切な Hooks ページにこのガイダンスが配置され、関数を直接渡すとなぜその関数が呼び出されるのかが明確に説明されていれば完了です。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
javascript, react
領域
documentation
issue の種類
ドキュメント
難易度
3/5
見積もり時間
1〜2日
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
45/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。