LoginSignup
2
0

More than 3 years have passed since last update.

Jotai v0.16.1に入ったRedux integrationとは何か

Last updated at Posted at 2021-04-22

先日 jotai v0.16.1 をリリースしました。

実験的位置付けの3つのintegrationバンドルが含まれています。

  • jotai/valtio
  • jotai/zustand
  • jotai/redux

混乱させないか悩んだところでもあるのですが、利用シーンはあると思うので入れました。

jotai/reduxの例を紹介します。実装はシンプルです。v0.16.2で少し修正しましたが、こんな感じです。

export function atomWithStore(store) {
  const baseAtom = atom(store.getState())
  baseAtom.onMount = (setValue) => {
    const callback = () => {
      setValue(store.getState())
    }
    const unsub = store.subscribe(callback)
    callback()
    return unsub
  }
  const derivedAtom = atom(
    (get) => get(baseAtom),
    (_get, _set, action) => {
      store.dispatch(action)
    }
  )
  return derivedAtom
}

これをどのように使うかですが、もっとも簡単なstoreを考えてみましょう。

import { createStore } from 'redux'

const initialState = { count: 0 }
const reducer = (state = initialState, action) => {
  if (action.type === 'INC') {
    return { ...state, count: state.count + 1 }
  }
  return state
}
const store = createStore(reducer)

これを、react-reduxで使う場合は、次のようになると思います。

import { Provider, useSelector, useDispatch } from 'react-redux'

const Counter = () => {
  const count = useSelector((state) => state.count)
  const dispatch = useDispatch()
  return (
    <div>
      count: {count}
      <button onClick={() => dispatch({ type: 'INC' })}>button</button>
    </div>
  )
}

const App = () => (
  <Provider store={store}>
    <Counter />
  </Provider>
)

同じものをjotai/reduxで書くと次のようになります。

import { Provider, atom, useAtom } from 'jotai'
import { atomWithStore } from 'jotai/redux'

const storeAtom = atomWithStore(store)
const countAtom = atom(
  (get) => get(storeAtom).count,
  (_get, set, action) => set(storeAtom, action)
)

const Counter = () => {
  const [count, dispatch] = useAtom(countAtom)
  return (
    <div>
      count: {count}
      <button onClick={() => dispatch({ type: 'INC' })}>button</button>
    </div>
  )
}

const App = () => (
  <Provider>
    <Counter />
  </Provider>
)

違いがわかりますか。ほとんど違いがないと思った方がいらしたら、それは正解です。同じように使えることを目指したので。

違いは何か、atomになったので、他のatomと合わせたり、他のjotaiの関数が使えることになります。いかがでしょう。新規にアプリを作る場合はあまり使わないとは思いますが、既存のreact-reduxアプリからの移行は簡単になるかもしれません。

jotaiはv1リリースを目指して最終段階の開発中です。興味がある方はぜひ試してみてください。

「React Fan」というコミュニティを立ち上げていて、そのSlackでもjotaiに関する議論や質問ができますので、よろしければご参加ください。

詳しくは、下記のページをご参照ください。

React開発者向けオンラインサロン「React Fan」の入り口ページ

Slackへの招待リンクも上記ページにあります。

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