reactjs / reactjs/react.dev

Request for clarification: can ref initialization code (lazy or not) contain side effects?

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

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

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ả

New docs on avoiding recreating ref contents has two examples:

Example1:

const playerRef = useRef(new VideoPlayer());

Example2:

const playerRef = useRef(null);
if (playerRef.current === null) {
  playerRef.current = new VideoPlayer();
}

Even the old docs have similar examples:

Example3:

const ref = useRef(new IntersectionObserver(onIntersect));

Example4:

const ref = useRef(null);
if (ref.current === null) {
   ref.current = new IntersectionObserver(onIntersect);
}

Both new VideoPlayer() and new IntersectionObserver(onIntersect) look like calls that might contain side effects inside.
My question is it allowed in any of the above examples, for these calls to contain side effects?

  • imho in Examples 1/3 they should not because they are executed on each render; although only values from initial render are kept.

  • But examples 2/4 suggest a pattern which make reading and writing to refs ok - which normally is an impure operation already. So I thought maybe in those examples at least, it is ok for new VideoPlayer() and new IntersectionObserver(onIntersect) to contain side effects?

It would be helpful if the docs clarified this.

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

Bắt đầu với phần hiện tại về useRef, “avoiding recreating the ref contents”, và phần được liên kết trong Legacy Hooks FAQ về việc tạo các đối tượng tốn kém một cách lazy. So sánh cả bốn ví dụ và kiểm tra hướng dẫn của React về các side effect trong thời gian render. Hoàn thành khi tài liệu giải thích rõ liệu các mẫu khởi tạo này có thể chứa side effect hay không và phân biệt hành vi của chúng.

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
42/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.