1
0

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 5 years have passed since last update.

React hooksとuse-immerを使いながらTypescriptでreduxっぽいことをする

Posted at

use-immer
https://github.com/immerjs/use-immer

テストrepo
https://github.com/github0013/react-hooks-immer-redux-typescript
yarn && yarn developで動きます

  1. reducerを作る
    リンク1
  2. use-immerのuseImmerReducerを使ってstateとdispatchを作る
    リンク2
  3. contextを使って、stateとdispatchを保持する
    リンク3
    https://reactjs.org/docs/context.html
  4. useContextを使ってを参照する
    リンク4
    https://reactjs.org/docs/hooks-reference.html#usecontext

問題

通常reducer内ではstateimmutableにする為に、

  switch (action.type) {
    case "some_action_name":
      return [...state, abc: new_value]

などとする必要がある。結構面倒

useImmerReducerだと...

これをuse-immerのuseImmerReducerを使う事で


  switch (action.type) {
    case "some_action_name":
      // 直接stateをいじれる上に、returnする必要すら無い
      state.abc = new_value

として、処理が簡単にかける。

1
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?