reactjs / reactjs/react.dev

When would we use "useImperativeHandle" in ReactJs' hooks?

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

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

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

説明

I am trying to understand what ReactJs' team expects from developers when using the useImperativeHandle's method. Currently the documentation indicates that:

imperative code using refs should be avoided in most cases. useImperativeHandle should be used with forwardRef.
Does this means it is good practice to use useImperativeHandle with forwardRef ? When would we use useImperativeHandle typically?
More specifically, in this discussion on stackoverflow about how calling child's methods from parents , someone provided this answer which propose to use useImperativeHandle . Then some comments argued that this is not good practice:

This is not really a good pattern. {...} It's better to pass props into the child component and then have a button click in the parent change the parent's state, and pass a state item into the child which will trigger the child's componentWillReceiveProps, and use that as a trigger.
No, it's not usually the best pattern, it's more of an escape hatch when you need it, and should be used only in emergencies.{...}

I would we make the things limpid for everyone, so here my specifics questions:

  • Is it good practice to use useImperativeHandle with forwardRef ?

  • When would we use useImperativeHandle typically?

  • Can we, or not, safely use useImperativeHandle for the convenience of easily communicate properties and methods to the childs' parents?

  • Why the documentation say that imperative code using refs should be avoided in most cases. useImperativeHandle should be used with forwardRef.?

  • What are the information to know to make an educated decision about the usage of useImperativeHandle?

  • lastly, is it safer, safe, and even a good practice to use the useEffect's method to communicate element to parents, like in the following demo, here a relevant's snippet:


 useEffect(() => {
    ref.current = { componentState }; // get a forwardRef's reference, then transmit some state to parent by modifying the reference
    validateChildren(ref.current.componentState.two);
  });

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

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

はじめの一歩

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

調査の方向性

リポジトリのファイルもテストも指定されていません。まず useImperativeHandle と forwardRef のドキュメント、リンクされた Stack Overflow のディスカッション、StackBlitz の例を確認し、意図されたガイダンスを判断してください。完了とは、適切な使用方法と代替手段について、明確で正確なドキュメントによって、列挙された質問を解決することです。

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

評価

技術スタック
javascript, react
領域
documentation
issue の種類
ドキュメント
難易度
5/5
見積もり時間
1週間以上
活発さ
停滞
明瞭さ
説明が足りない
初心者へのやさしさ
25/100

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

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