reactjs / reactjs/react.dev

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

Đang mở
#6,925 1 bình luận 0 reaction 0 người được giao Xem trên GitHub

Chưa có ai nhận issue này.

type: documentation
Ngôn ngữ chính
JavaScript
Star
11.8k
Fork
7.9k
Merge trung bình
1 ngày 11 giờ
Pull request đã merge (30 ngày)
11

Mô tả

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

Hướng dẫn đóng góp

Mở hướng dẫn đóng góp

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Hướng nghiên cứu

Xem lại phần lưu ý về useRef tại https://react.dev/reference/react/useRef#caveats và so sánh hướng dẫn trong đó với issue của Apollo Client và phần triển khai useLatest được liên kết trong báo cáo. Làm rõ liệu có nên loại bỏ hay sửa đổi lưu ý này đối với các refs được đồng bộ trong quá trình render mà không ảnh hưởng đến giá trị trả về của component hay không, sau đó cập nhật tài liệu và xác minh rằng cách diễn đạt sau cùng là rõ ràng, không gây hiểu nhầm.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Đánh giá

Công nghệ
javascript, react
Lĩnh vực
documentation
Loại issue
Tài liệu
Độ khó
3/5
Thời gian dự kiến
1-2 ngày
Mức độ hoạt động
Đình trệ
Độ rõ ràng
Khá rõ ràng
Mức phù hợp với người mới
35/100

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.