1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

React公式の「state とライフサイクル」のclassをhooksを使って関数に書き換えしてみた

Last updated at Posted at 2020-02-29

#概要
classで書かれているcomponentDidMountとcomponentWillUnmountを useEffect を使って関数にしてみます。stateはuseStateを使って管理します。
実行される内容はタイマーで時間を動的に刻まれていくものです。

React公式
https://ja.reactjs.org/docs/state-and-lifecycle.html

公式からソースを抜粋


class Clock extends React.Component {
    constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  componentDidMount() {
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  }

  componentWillUnmount() {
    clearInterval(this.timerID);
  }

  tick() {
    this.setState({
      date: new Date()
    });
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

ReactDOM.render(
  <Clock />,
  document.getElementById('root')
);

こちらを関数に書き換えます。


const Clock: React.FC = () => {
  let [state, setState] = React.useState({ date: new Date() });
  const dateObj = { date: new Date() };
  let timerID: any;

  useEffect(() => {
    timerID = setInterval(() => tick(), 1000);
    return () => {
      clearInterval(timerID);
    };
  });

  function tick() {
    setState({ date: new Date() });
  }

  return (
    <div className="App">
      <h1>Hello, world!</h1>
      <h2>It is {dateObj.date.toLocaleTimeString()}</h2>
    </div>
  );
};

useEffectがcomponentDidMountとcomponentWillUnmountの役割を果たしています。

詳しくは「副作用フックの利用法」読むと良いです。
https://ja.reactjs.org/docs/hooks-effect.html

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?