reactjs / reactjs/react.dev

[Suggestion]: remove the caveat for writing ref in render path

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

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

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

説明

Summary

In the doc for ref https://react.dev/reference/react/useRef#caveats, it calls out to not read/write ref in rendering phase without a very clear "bad example"

Page

No response

Details

However, there is use case where the caller just needs a static ref at component level to wrap a dynamic value: for example, I need to read/write a static ref in rendering path (keep it in-sync with the current render context value)

In another word, the argument could be "a need to read/sync a "render context" value into a static variable attached to the functional component", + the "ref" value is not use in the "return" of the functional component

const { componentId, renderId } = useContext(componentContext);
const context = { componentId, renderId } <--- dynamic

const contextRef  =  useRef(context); <--- static
contextRef.current = context;

useQuery({
  context: contextRef  <--- static ref to avoid equal check, the ref value is only used for logging
})

e.g. https://github.com/apollographql/apollo-client/issues/11835

and there are popular library like useLatest implemented by writing ref in render path

Can we remove or update the caveat to make it more clear? E.g. adding

If you don't attempt to use the "mutable" ref in determining the function return, it is fine to use it to sync rendering context

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

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

はじめの一歩

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

調査の方向性

https://react.dev/reference/react/useRef#caveats の useRef の注意事項セクションを確認し、その説明をレポート内でリンクされている Apollo Client の issue および useLatest の実装と比較してください。コンポーネントの返り値に影響を与えずにレンダリング中に同期される refs について、この注意事項を削除または改訂すべきかを明確にしたうえで、ドキュメントを更新し、更新後の文言が曖昧でないことを確認してください。

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

評価

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

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

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