v16.8からHooksが追加されたって、ニュースに出てたので試してみます。

参考にしたのはここ「Introducint Hooks」今日は、StateHookというやつをみていきます。

実装

なんか、built-in hookに useStateというのがあって、コレを使えば、classなしでもstate使える。

We call it inside a function component to add some local state to it. 

Introduction hooks

index.json

import React, { useState } from "react";
import ReactDOM from "react-dom";

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

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

ReactDOM.render(<App />, document.getElementById("app"));

index.html

<!DOCTYPE html>
<html>
  <head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
  </head>
  <body>
    <div id="app"></div>
    <script src="src/index.js"></script>
  </body>
</html>

package.json

{
  "name": "parcel-sandbox",
  "version": "1.0.0",
  "description": "Simple Parcel Sandbox",
  "main": "index.html",
  "scripts": {
    "start": "parcel index.html --open",
    "build": "parcel build index.html"
  },
  "dependencies": {
    "react": "16.8.1",
    "react-dom": "16.8.1"
  },
  "devDependencies": {
    "@babel/core": "7.2.0",
    "@types/react": "16.8.1",
    "@types/react-dom": "16.8.1",
    "parcel-bundler": "^1.6.1"
  }
}

動作確認 (codesandbox)