reactjs / reactjs/react.dev

React docs on useEffect

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

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

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

説明

The docs have an example about using useEffect with cleanup, here.

If I carry out the sequence, then I would get
run effect -> subscribe to update from ChatApi -> setIsOnline -> cleanup -> run effect -> subscribe to update from ChatApi -> setIsOnline

I am unsure as to why this does not lead to an infinite loop without use of the dependency array?

One understanding / theory that I have is:
The first time the subscription cause setIsOnline(true). Next time (after one cycle of unsubscribe/effect), the setIsOnline gets argument as true and hence further update to the component does not occur. This is assuming that this form of setIsOnline does not re-render if the isOnline has not changed (it is still true).

I am curious as to why the piece of code is correct.

Here it is as copied from the useEffect documentation

import React, { useState, useEffect } from 'react';

function FriendStatus(props) {
  const [isOnline, setIsOnline] = useState(null);

  useEffect(() => {
    function handleStatusChange(status) {
      setIsOnline(status.isOnline);
    }
    ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
    // Specify how to clean up after this effect:
    return function cleanup() {
      ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
    };
  });

  if (isOnline === null) {
    return 'Loading...';
  }
  return isOnline ? 'Online' : 'Offline';
}

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

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

はじめの一歩

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

調査の方向性

リンク先の useEffect ドキュメントの例から始め、説明されている subscription、cleanup、setIsOnline の順序を確認してください。例に再レンダーの動作の説明が必要なのか、改訂した例が必要なのかを明確にし、その後、期待される effect のライフサイクルと完了基準が明示されるようにドキュメントを更新してください。

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

評価

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

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

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