React hooksとは
React 16.8 で追加された新機能です。
クラスを書かなくても、 state
などのReactの機能を、関数コンポーネントでシンプルに扱えるようになりました。
React hooksのうち、実際によく使用される3つに絞って紹介します。
- React hooksを基礎から理解する (useState編)
今ここ
- React hooksを基礎から理解する (useEffect編)
- React hooksを基礎から理解する (useContext編)
クラスコンポーネントと関数コンポーネント
クラスコンポーネントと関数コンポーネントの違いを確認してみます。
クラスコンポーネント
import React from 'react'
const intialState = Math.floor(Math.random() * 10) + 1
// countの初期値として、1~10までのランダムな数値を生成
class Counter extends React.Component {
constructor(props) {
super(props)
this.state = {
count: intialState,
// クラスでは、コンストラクタ内で、this.stateの初期値{ count: intialState }をセット
open: true
// this.stateの初期値{ open: false }をセット
}
}
toggle = () => {
this.setState({ open: !this.state.open })
}
// toggleメソッドを作成
render() {
return (
<>
<button onClick={this.toggle}>
{this.state.open ? 'close' : 'open'}
</button>
<div className={this.state.open ? 'isOpen' : 'isClose'}>
<p>現在の数字は {this.state.count} です</p>
<button
onClick={() => this.setState({ count: this.state.count + 1 })}
>
+ 1
</button>
<button
onClick={() => this.setState({ count: this.state.count - 1 })}
>
- 1
</button>
<button onClick={() => this.setState({ count: 0 })}>0</button>
<button onClick={() => this.setState({ count: intialState })}>
最初の数値に戻す
</button>
{/*ボタンをクリックした時に、this.setState()を呼ぶことでcountステートを更新 */}
</div>
</>
)
}
}
export default Counter
関数コンポーネント
hooks の useState
を使ってクラスコンポーネントから関数コンポーネントに書き換えてみます。
関数コンポーネントの基本形は以下の通り。
const ExComponent = props => {
// ここでhooksを使える
return <div />
}
useStateの基本形
useState
によって React の state
の機能を関数コンポーネントに追加します。
const [count, setCount] = useState(intialState)
左辺の state 変数には任意の名前を付けることが出来ます。
(分割代入構文をイメージすると理解しやすいです。)
- 1つ目の要素:
state
の現在値 - 2つ目の要素: それを更新するための関数
-
state
が更新されてもintialState
はintialState
として保持される
import React, { useState } from 'react'
// 関数コンポーネント内で state を使えるようにするため、useState を インポート
const Counter = () => {
const intialState = Math.floor(Math.random() * 10) + 1
// countの初期値として、1~10までのランダムな数値を生成
const [count, setCount] = useState(intialState)
// state という名前の state 変数を宣言、初期値intialStateをセット
const [open, setOpen] = useState(true)
// open という名前の state 変数を宣言、初期値trueをセット
const toggle = () => setOpen(!open)
// toggleの関数を宣言
return (
<>
<button onClick={toggle}>{open ? 'close' : 'open'}</button>
<div className={open ? 'isOpen' : 'isClose'}>
<p>現在の数字は{count}です</p>
<button onClick={() => setCount(prevState => prevState + 1)}>
{/* setCount()は、countを更新するための関数。countを引数で受け取ることも出来る */}
+ 1
</button>
<button onClick={() => setCount(count - 1)}>- 1</button>
<button onClick={() => setCount(0)}>0</button>
<button onClick={() => setCount(intialState)}>最初の数値に戻す</button>
</div>
</>
)
}
export default Counter
クラスで書いた場合と、同じ結果になりました
再レンダリング後も React はその変数の現在の state
の値をそのまま持っており 、最新の state
の値を関数に渡します。現在の state
の値を更新したい場合は、setState
を呼びます。
最後に
次回は useEffect
について書きたいと思います。