LoginSignup
5
4

More than 3 years have passed since last update.

Redux-hooks【短編】

Last updated at Posted at 2019-07-25

概要

Reactで開発するにあたってHooksちゅう新しい機能を使うので、勉強したことをメモ的に投稿していこうと思います。

公式ドキュメント

React Redux(Hooks)

トピックス
・useSelector
・useDispatch

useSelector

selecter関数をしてStoreのstateからデータを取得します。
useSelectorはStoreを監視し、アクションがディスパッチされるたびにselecter関数を実行します。

例:useSelector

useSelector
 const selector = state => state.name;
 const name = useSeletor(selector);

useDispatch

Storeからdispatch関数を返します。
dispatch関数を使用してアクションをディスパッチできます。

例:useDispatch

useDispatch
 const dispatch = useDispatch();
 dispatch({ type: "LOGIN", 'くいだおれ太郎' });

useSelector & useDispatch

実際に使ってみたサンプル

example.jsx
import React from "react";
import { useDispatch, useSelector } from "react-redux";

const Example = () => {
    /* useSelector */
    const name = useSeletor(state => state.name);
    /* useDispatch */
    const dispatch = useDispatch();

    return(
        <>
            <h1>NAME: {name}</h1>
            <input
                type="text"
                onChange={event =>
                    dispatch({ type: "NAME", event.target.value })} />
        </>
    );
}

ざっくりまとめ

Action, Reducerの設定は今まで通り必要ですが、connect関数を使用した、めんどくさい設定がいらんようなって楽チンになりました。

5
4
1

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
5
4