LoginSignup
13
10

More than 5 years have passed since last update.

React Hooksを触ってみた - State Hooks

Last updated at Posted at 2018-10-28

概要

Reactの新機能、React Hooksのうち、State Hooksの紹介

React Hooksとは?

React Hooksとは、React Ver 16.7 から導入される、クラスを書かずに state 管理を行える機能。
現在、Reactの 16.7.0-alpha.0 で機能を試すことができる。(10/28/18 現在)

React Hooksを使って見るには?

手っ取り早く機能を試すには、create-react-appで新規reactアプリを作成すること。
そのままだと現時点でのlatestである16.6.0が入っているので、@next版を入れる(10/29/18現在)

yarn add react@next react-dom@next

とりあえずExampleの実装

Reactの公式サイトに乗っているCounterの実装例を書いてみる
Code Sandboxはこちら

app.jsx
import React, { useState } from 'react'
import ReactDOM from 'react-dom'

const App = () => {
  const [count, setCount] = useState(0)

  return (
    <div>
      <p>You clicked {count} times </p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
}

const rootElement = document.getElementById("root")
ReactDOM.render(<App />, rootElement)

つまりどういうことだってばよ?

まずは最初の行を見てほしい

const [count, setCount] = useState(0)

ここでCounterの値を保持するstate名、countとそれと対になるSetter関数であるsetCountが宣言されている。
useState()に使われている引数は宣言したStateの初期値だ。
ボタンを押す度にsetCountが呼ばれてcountの値が更新される。

<button onClick={() => setCount(count + 1)}>Click me</button>

何が良くなったの?

今までのstateful componentと比べて格段にコードが短く済むようになったのと、
Classでは無いので、至るところでthisを書かなくても良くなり、とっつきやすくなった。
参考までに上記のコードを今までのReactの手法で書いたらこうなる。

app.jsx
import React, { Component } from "react";
import ReactDOM from "react-dom";

class App extends Component {
  constructor() {
    super();
    this.state = { count: 0 };
  }

  setCount(val) {
    this.setState({ count: val });
  }

  render() {
    const { count } = this.state;
    return (
      <div>
        <p>You clicked {count} times </p>
        <button onClick={() => this.setCount(count + 1)}>Click me</button>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

他の機能は?

今回紹介したのはReact Hooksの基本であるState管理を行う為の機能、State Hooks
React Hooksには他に以下の機能がある
- Effect Hooks - クラスを宣言しなくてもStateの状態をListenしてState以外の操作が行える
- Custom Hooks - 他のComponentで流用できるHooks
これらについてはまた後日記述する。

参考

Hooks at a Glance - React
Introducing Hooks - React
Writing Custom Hooks - React

13
10
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
13
10