LoginSignup
0
0

More than 1 year has passed since last update.

React Hooks (状態のフック)

Posted at

概要

React Hooks 状態のフックについてまとめました。

状態のフック

内部の状態を保持して、その状態の変化を表示するフック

■useState

状態を扱うためのフック

第1引数に渡した値が初期値となる。
戻り値は配列となっており、1つ目が現在の状態、2つ目が更新関数。

import { useState } from 'react'
// typescript
type DispStrProps = {
    initValue: string
}

const Display = (props: DispStrProps) => {
    const { initValue } = props
    const [dispStr, setDispStr] = useState(initValue)

    return (
        <div>
            <p>input: {dispStr}</p>
            <input type="text" onChange={(e) => setDispStr(e.target.value)} />
        </div>
    )
}

export default Display

■useReducer

状態を扱うもう1つのフック
配列やオブジェクトなどの複数のデータのまとまりを扱うことが多い。
第1引数にReducer関数、第2引数に初期値
useStateのセット関数と比べて下記メリットがある。
・関数を切り出せる。
・具体的な状態に依存しない

import { useReducer } from 'react'

type Action = 'INCREMENT' | 'MULTIPLICATION' 
const reducer = (count: number, action: Action) => {
    switch (action) {
        case 'INCREMENT':
            return count + 1
        case 'MULTIPLICATION':
            return count * 2
        default:
            return count
    }
}


const Counter = () => {
    const [count, dispatch] = useReducer(reducer, 0)

    return (
        <div>
            <p>count: {count}</p>
            <button onClick={() => dispatch('INCREMENT')}>+</button>
            <button onClick={() => dispatch('MULTIPLICATION')}>×</button>
        </div>
    )
}

export default Counter
0
0
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
0
0