1
Help us understand the problem. What are the problem?

More than 1 year has passed since last update.

posted at

updated at

Organization

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

概要

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

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Sign upLogin
1
Help us understand the problem. What are the problem?