Reactガイドを読んでいくその255

これは

Reactのガイドを読んでいく記事です。

ガイドのリンク

ja.reactjs.org

副作用を使う場合のヒント

React経験者向きのuseEffectについての説明になるらしい。

ヒント:関心を分離するために複数の副作用を使う

フック導入の動機はライフサイクルメソッドに関連のないロジックが含まれる一方で、
関連するロジックが複数のメソッドに分割されてしまうという問題があるため。

class FriendStatusWithCounter extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0, isOnline: null };
    this.handleStatusChange = this.handleStatusChange.bind(this);
  }

  componentDidMount() {
    document.title = `You clicked ${this.state.count} times`;
    ChatAPI.subscribeToFriendStatus(
      this.props.friend.id,
      this.handleStatusChange
    );
  }

  componentDidUpdate() {
    document.title = `You clicked ${this.state.count} times`;
  }

  componentWillUnmount() {
    ChatAPI.unsubscribeFromFriendStatus(
      this.props.friend.id,
      this.handleStatusChange
    );
  }

  handleStatusChange(status) {
    this.setState({
      isOnline: status.isOnline
    });
  }
  // ...

document.titleを設定するためのロジックが、 componentDidMountとcomponentDidUpdateに分離している点に注意する。
購読のためのロジックも同様に分離してしまっている。

フックでは以下のようにステートフックを複数回呼ぶのと同様に副作用を複数回呼ぶことができる。
そのため関係ないロジックは別の副作用に分けることで関連性のある同士を別々にすることを避けることができる。

function FriendStatusWithCounter(props) {
  const [count, setCount] = useState(0);
  useEffect(() => {
    document.title = `You clicked ${count} times`;
  });

  const [isOnline, setIsOnline] = useState(null);
  useEffect(() => {
    function handleStatusChange(status) {
      setIsOnline(status.isOnline);
    }

    ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
    return () => {
      ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
    };
  });
  // ...
}

フックでは何をやっているかに基づいてコードを分割することができる。

今日はここまで。