LoginSignup
2

More than 1 year has passed since last update.

posted at

updated at

Organization

redux-toolkitをreduxなしで使ってみる

こちらはVISITS advent calendar 2020 24日目の記事です。

本日はフロントエンドエンジニアのpipopotamsauがつとめさせていただきます。

本記事ではredux-toolkitでreduxを使わず、Reactの標準APIのみで使う方法をご紹介しようと思います。

1. redux-toolkitとは

redux-toolkitとはredux開発チームが公式に出している、より効率的かつ簡単にreduxを利用できるようにするライブラリになります。

redux-toolkitの詳しい説明は本記事の趣旨ではないため割愛しますが、名前からわかる通り基本的には「redux」と一緒に使うためのライブラリです。

しかし、reduxなしでReactのuseReducerと一緒に使うこともできるので紹介したいと思います。

2. redux-toolkitとuseReducerを組み合わせて使ってみる

それでは早速redux-toolkitとuseReducerを組み合わせたサンプルアプリケーションをみていきましょう。

以下のようなカウンターアプリを作ってみます。

スクリーンショット 0002-12-18 13.57.40.png

※ 本記事のサンプルアプリケーションのレポジトリはこちらです

まずはredux-toolkitのcreateSliceヘルパーを使用し、reducer、action creator、action typeを生成します。

import { createSlice } from '@reduxjs/toolkit';

const initialState = { counter: 0 };

const slice = createSlice({
  name: 'counter',
  reducers:{
    INCREMENT: (state) => {
      state.counter += 1;
    },
    DECREMENT: (state) => {
      state.counter -= 1;
    },
    RESET: (state) => {
      state.counter = 0;
    },
  },
  initialState
});

const { actions, reducer } = slice;

次は上記のcreateSliceで生成したreducerとuseReducerを組み合わせて、stateとdispatch関数を生成します。

const { actions, reducer } = slice;

function CounterApp() {
  const [state, dispatch] = useReducer(reducer, initialState);

  return (
    // return jsx
  );
}

ここまででほぼ終わりです。あとはcounterを表示したり、buttonのonClickイベントに上記で生成したdispatch関数とactionを組み合わせたコールバックを仕込むだけです。

const { actions, reducer } = slice;

function CounterApp() {
  const [state, dispatch] = useReducer(reducer, initialState);

  return (
    <div className="counter-app">
      <p className="counter">Counter: { state.counter }</p>
      <ul className="buttons">
        <li>
          <button onClick={ () => dispatch(actions.INCREMENT) }>+</button>
        </li>
        <li>
          <button onClick={ () => dispatch(actions.DECREMENT) }>-</button>
        </li>
        <li>
          <button onClick={ () => dispatch(actions.RESET) }>reset</button>
        </li>
      </ul>
    </div>
  );
}

これで以下のようなカウンターアプリを作ることができました:tada:

102450650-40a9f500-407a-11eb-8730-f24744af3dd6.gif

3. なぜredux-toolkitをuseReducerと一緒に使うのか?

基本的にreduxでredux-toolkitを使う理由と一緒だと考えています。

効率的にreducerやaction creators, action typeを作るためだったり、書き方を統一する意図で使用しています。

4. 終わりに

最後までお読みいただきありがとうございました。

本記事のサンプルコードは以下になります。コード全体がみたいという方はこちらを参照してください。
https://github.com/pipopotamasu/redux-toolkit-and-usereducer

さて、クリスマスまで残すところあと1日です。

VISITS Technologiesのアドベントカレンダーの最後を飾るのは、エンジニアリングマネージャーの@kotala_bになります!

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
What you can do with signing up
2