3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

React Hooks ~ State Hookの使い方 ~

Last updated at Posted at 2021-01-16

React を触っていて学んだことをまとめていきます。

React Hooks とは

これを用いることで、クラスコンポーネントでこれまで利用されてきたReactの機能を関数コンポーネントでも利用できるようになります。

React は長年書かれるうちに、シンプルに簡潔に書くこと、テストの容易性から、関数コンポーネントで書くことが主流になった。
しかし、当時の関数コンポーネントは React のライフサイクルメソッドなどを利用することができず、クラスコンポーネントの利用や併用、ライブラリの利用で解決していた。

React v16.8 でReact Hooks が導入された。
React Hooks がもたらした恩恵は

  • コンポーネントがシンプルになる
  • 関数として、コンポーネントからロジックを抽出、使い回しが用意になる。
  • class の this に悩まされなくなる

State Hook とは

コンポーネントに状態(State)を持たせたいときに利用する。
State は設定したコンポーネント内でのみ呼び出しができる。もし他コンポーネントにpropsとして渡してあげれば他コンポーネントからの表示、更新などが可能ではある。

State Hook の使い方

シンプルに書くならこんな感じで利用できる。

// useState を import する。
import { useState } from 'react'

const  CountButton = () => {
   // State の変数、更新のためのメソッド名を定義する。
   // useState(0) で State の初期値を設定できる。
   const [count, setCount] = useState(0)
   return (
    <div>
      {// 変数名で呼び出しができる。
      }
      <button onClick={() => setCount(count + 1)}>{count}</button>
    </div>
  )
}

TypeScript との併用

TypeSctipt との併用も、問題なく利用ができます。

const [count, setCount] = useState<number>(0)

子コンポーネントから、親コンポーネントの状態を更新する。

子コンポーネントに、propsとして、状態の値、コールバック関数を用いることで可能です.
こうすることで、他のコンポーネントでも再利用が可能な子コンポーネントの作成ができそうです。

App.tsx(親コンポーネント)
import React, { useState, useCallback } from "react"
import { InputForm } from "./InputForm"

export default function App() {
  const [ content, setContent ] = useState<string>("test")

  const onChangeContent = useCallback(
    (event: React.ChangeEvent<HTMLInputElement>) => {
      setContent(event.target.value)
    },
    [],
  )

  return (
    <div className="App">
      <InputForm content={content} onChange={onChangeContent} />
      <span>{content}</span>
    </div>
  )
}
InputForm.tsx(子コンポーネント)
import React from "react"

interface Props {
  content: string;
  onChange: (event: React.ChangeEvent<HTMLInputElement>) => void;
}

export const InputForm = (props: Props) => {
  return <input defaultValue={props.content} onChange={props.onChange}></input>
}

codesandbox に実際にうごく様子を公開しています。

3
3
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
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?