0
1

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×TypeScript×Firebase】Redux Toolkit

Posted at

Redux Toolkitの使用方法

  • Redux Toolkitの導入にあたり、流れや使用方法、実際の作成について備忘録を残します。
  • 備忘録はカウンターアプリを例にします。

導入

  • Reduxを簡単に使うためのkit
npm install @reduxjs/toolkit
  • useDispatch等が用意されているhooks
npm install react-redux

概要

Redux toolkitで必要なファイル

  1. store.ts
  2. コンポーネント.tsx(ここではCounter.tsx)
  3. Slice(ここではconterSlice.tsx)

store.ts

  • 状態を管理するファイル
store.ts
import { configureStore } from '@reduxjs/toolkit'
import counterReducer from '../features/counterSlice';

export const store = configureStore({
    reducer:{
        counter: counterReducer,
    },
});

Counter.tsx

  • コンポーネントにあたる
Counter.tsx
import React from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { decrement, increment } from '../../features/counterSlice';
import { RootState } from '../../app/store';

const Counter = () => {
    const count = useSelector((state: RootState) => state.counter.value)
    const dispatch = useDispatch(); // 通知を出すことができるhooksがreact reduxに用意されている
  return (
    <div>
        <h1>count: {count}</h1>
        <button onClick={() => dispatch(increment())}>+</button>
        <button onClick={() => dispatch(decrement())}>-</button>
    </div>
  )
}

export default Counter

conterSlice.tsx

  • スライス(ActionCreater, State, Reducer)をまとめたもの
conterSlice.tsx
import { createSlice } from "@reduxjs/toolkit";

interface CounterState {
    value: number;
  }

  const initialState: CounterState = {
    value: 0,
  };

// creatSlice actionCreater, dithpach, reducerを一度に作ることができる関数(用意されている)
export const counterSlice = createSlice({
    name: "counter",    // sliceの名前
    initialState,
    reducers:{          // 状態を更新するための関数みたいなもの actionCreaterはreducerを作成すると同じ名称で自動的に裏で作成される
        increment: (state) => {     // カウントアップ stateはその時々の状態
            state.value += 1;
        },
        decrement: (state) => {
            state.value -= 1;
        },
    }
})

export const { increment, decrement } = counterSlice.actions; //actionCreaterはコンポーネントに受け渡さないといけないのでexport
export default counterSlice.reducer; // redusersではなくreducersを渡す
0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?