assigning a function to a `useState` variable
まだ誰も着手していません。
- 主要言語
- 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!
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
まず、useState と useEffect に関連する React Hooks ドキュメントのセクションを見つけます。issue に示されている動作を文書化します。state に関数を保存するには、その関数を返す updater callback が必要であること、および setup と cleanup のユースケースを説明します。適切な Hooks ページにこのガイダンスが配置され、関数を直接渡すとなぜその関数が呼び出されるのかが明確に説明されていれば完了です。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- javascript, react
- 領域
- documentation
- issue の種類
- ドキュメント
- 難易度
- 3/5
- 見積もり時間
- 1〜2日
- 活発さ
- 停滞
- 明瞭さ
- おおむね明確
- 初心者へのやさしさ
- 45/100