react hook を5分で使う

この記事の一部を参照して、良さそうと感じた。stateがクラス以外で使える

import React from 'react'

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

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

export default App
import React, { useState } from 'react'

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

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

export default App

すごい便利そう。ということで試してみた

ためしてみた

npm init next-app nextjs-blog --example "https://github.com/zeit/next-learn-starter/tree/master/learn-starter"
cd nextjs-blog
npm run dev

アクセス

これで動くものができたので、react hookを試す

現在のdirectoryはnextjs-blogだと思う

mkdir components
touch components/example.js

 おきにいりのエディタでexample.jsを編集します

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

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

次に、pages/index.jsに2行追加

import Head from 'next/head'
import Example from '../components/example' // add

```
        <p className="description">
          Get started by editing <code>pages/index.js</code>
        </p>
        <Example/> // add

ok

画面中央にclick meボタンが追加された。

reactはconstructorを書くのが使いづらいなと思っていたが、楽になってよかった。使いやすい

参照

最終更新