エコシステム
Reduxは小さなライブラリですが、契約とAPIはツールや拡張機能のエコシステムを生成するために注意深く選択されており、コミュニティはさまざまな役立つアドオン、ライブラリ、ツールを作成しました。Reduxを使用するためにこれらのアドオンを使用する必要はありませんが、それらは機能を実装し、アプリケーションの問題を解決するのを容易にするのにも役立ちます。
Redux関連のライブラリ、アドオン、ツールの広範なカタログについては、Reduxエコシステムリンクリストを確認してください。また、React/Reduxリンクリストには、ReactまたはReduxを学習する人のためのチュートリアルやその他の有益なリソースが含まれています。
このページには、Reduxメンテナンス担当者が個人的に審査した、またはコミュニティで広く採用されているRedux関連のアドオンの一部が記載されています。躊躇せずに残りのアドオンを試してみましょう!エコシステムは急速に成長しており、すべてを確認する時間は限られています。これらを「編集者の選択」と見なし、Reduxを使用して素晴らしいものを作成した場合に遠慮なくPRを送信してください。
目次
ライブラリの統合とバインディング
reduxjs/react-redux
Reduxチームが保守するReactの公式バインディング
angular-redux/ng-redux
Redux用のAngular 1のバインディング
ember-redux/ember-redux
Redux用のEmberのバインディング
glimmer-redux/glimmer-redux
EmberのGlimmerコンポーネントエンジン用のReduxバインディング
tur-nr/polymer-redux
Polymer用のReduxバインディング
lastmjs/redux-store-element カスタムエレメント用のReduxバインディング
Reducer
Reducerの組み合わせ
ryo33/combineSectionReducers combineReducers
の拡張バージョン。これにより、3番目の引数としてstate
をすべてのスライスReducerに渡すことができます。
KodersLab/topologically-combine-reducers
順序付けとデータのやり取りを行うためにスライス間の依存関係を定義できるcombineReducers
の変種
var masterReducer = topologicallyCombineReducers(
{ auth, users, todos },
// define the dependency tree
{ auth: ['users'], todos: ['auth'] }
)
Reducerの構成
acdlite/reduce-reducers
同じレベルで逐次的にReducerを構成します
const combinedReducer = combineReducers({ users, posts, comments })
const rootReducer = reduceReducers(combinedReducer, otherTopLevelFeatureReducer)
mhelmer/redux-xforms
Reducer Transformerのコンポーザブルコレクション
const createByFilter = (predicate, mapActionToKey) =>
compose(
withInitialState({}), // inject initial state as {}
withFilter(predicate), // let through if action has filterName
updateSlice(mapActionToKey), // update a single key in the state
isolateSlice(mapActionToKey) // run the reducer on a single state slice
)
adrienjt/redux-data-structures
一般的なデータ構造のReducerファクトリ関数: counter、map、list (queue、stack)、set
const myCounter = counter({
incrementActionTypes: ['INCREMENT'],
decrementActionTypes: ['DECREMENT']
})
高階Reducer
omnidan/redux-undo
Reducer用の労力をかけずに取り消し/やり直し、およびアクション履歴
omnidan/redux-ignore
配列またはフィルター関数でReduxアクションを無視
omnidan/redux-recycle
特定のアクションでRedux Stateをリセット
ForbesLindesay/redux-optimist
タイプに依存しない楽観的な更新を有効にするReducerエンハンサー
ユーティリティ
reduxjs/reselect
ストアStateから効率的にデータを派生するためのコンポーザブルなメモ化されたセレクター関数を作成
const taxSelector = createSelector(
[subtotalSelector, taxPercentSelector],
(subtotal, taxPercent) => subtotal * (taxPercent / 100)
)
paularmstrong/normalizr
ネストしたJSONをスキーマに従って正規化
const user = new schema.Entity('users')
const comment = new schema.Entity('comments', { commenter: user })
const article = new schema.Entity('articles', {
author: user,
comments: [comment]
})
const normalizedData = normalize(originalData, article)
planttheidea/selectorator
一般的なセレクターユースケースに対するReselect上の抽象化
const getBarBaz = createSelector(
['foo.bar', 'baz'],
(bar, baz) => `${bar} ${baz}`
)
getBarBaz({ foo: { bar: 'a' }, baz: 'b' }) // "a b"
Store
変更のサブスクリプション
jprichardson/redux-watch
キーパスまたはセレクターに基づいてステートの変更を監視
let w = watch(() => mySelector(store.getState()))
store.subscribe(
w((newVal, oldVal) => {
console.log(newval, oldVal)
})
)
ashaffer/redux-subscribe
パスに基づいてステートの変更に対する集中管理サブスクリプション
store.dispatch( subscribe("users.byId.abcd", "subscription1", () => {} );
バッチ処理
tappleby/redux-batched-subscribe
サブスクリプション通知をデバウンスできるストアエンハンサー
const debounceNotify = _.debounce(notify => notify())
const store = configureStore({
reducer,
enhancers: [batchedSubscribe(debounceNotify)]
})
manaflair/redux-batch
アクションの配列をディスパッチできるストアエンハンサー
const store = configureStore({
reducer,
enhancers: existingEnhancersArray => [
reduxBatch,
...existingEnhancersArray,
reduxBatch
]
})
store.dispatch([{ type: 'INCREMENT' }, { type: 'INCREMENT' }])
laysent/redux-batch-actions-enhancer
バッチ化されたアクションを受け入れるストアエンハンサー
const store = configureStore({ reducer, enhancers: [batch().enhancer] })
store.dispatch(createAction({ type: 'INCREMENT' }, { type: 'INCREMENT' }))
tshelburne/redux-batched-actions
バッチ化されたアクションを処理する高階Reducer
const store = configureStore({ reducer: enableBatching(rootReducer) })
store.dispatch(batchActions([{ type: 'INCREMENT' }, { type: 'INCREMENT' }]))
永続化
rt2zz/redux-persist
柔軟な拡張オプションを使用して、Redux Storeを永続化してリカバリー
const persistConfig = { key: 'root', version: 1, storage }
const persistedReducer = persistReducer(persistConfig, rootReducer)
export const store = configureStore({
reducer: persistedReducer,
middleware: getDefaultMiddleware =>
getDefaultMiddleware({
serializableCheck: {
ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER]
}
})
})
export const persistor = persistStore(store)
react-stack/redux-storage
柔軟なバックエンドを使用したReduxの永続化レイヤー
const reducer = storage.reducer(combineReducers(reducers))
const engine = createEngineLocalStorage('my-save-key')
const storageMiddleware = storage.createMiddleware(engine)
const store = configureStore({
reducer,
middleware: getDefaultMiddleware =>
getDefaultMiddleware.concat(storageMiddleware)
})
redux-offline/redux-offline
オプティミスティックUIをサポートするオフラインファーストアプリ用の永続ストア
const store = configureStore({ reducer, enhancer: [offline(offlineConfig)] })
store.dispatch({
type: 'FOLLOW_USER_REQUEST',
meta: { offline: { effect: {}, commit: {}, rollback: {} } }
})
不変データ
ImmerJS/immer
プロキシを使用して通常のミュータブルコードで不変の更新
const nextState = produce(baseState, draftState => {
draftState.push({ todo: 'Tweet about it' })
draftState[1].done = true
})
副作用
広く使用されているもの
reduxjs/redux-thunk dispatch
およびgetState
を引数として渡されるディスパッチ関数です。これにより、AJAXコールやその他の非同期処理方法の抜け穴ができます。
最適用途: スタート、単純な非同期および複雑な同期ロジック
function fetchData(someValue) {
return (dispatch, getState) => {
dispatch({type : "REQUEST_STARTED"});
myAjaxLib.post("/someEndpoint", {data : someValue})
.then(response => dispatch({type : "REQUEST_SUCCEEDED", payload : response})
.catch(error => dispatch({type : "REQUEST_FAILED", error : error});
};
}
function addTodosIfAllowed(todoText) {
return (dispatch, getState) => {
const state = getState();
if(state.todos.length < MAX_TODOS) {
dispatch({type : "ADD_TODO", text : todoText});
}
}
}
listenerMiddleware (Redux Toolkit)
listenerMiddleware は、saga や observable といったより広く使用される Redux 非同期ミドルウェアに代わる軽量な代替手段です。複雑さのレベルやコンセプトにおいてthunkに似ていますが、一般的な saga 使用パターンを複製するために使用できます。
listenerMiddleware.startListening({
matcher: isAnyOf(action1, action2, action3),
effect: (action, listenerApi) => {
const user = selectUserDetails(listenerApi.getState())
const { specialData } = action.meta
analyticsApi.trackUsage(action.type, user, specialData)
}
})
redux-saga/redux-saga
同期風ジェネレーター関数を用いて非同期ロジックを処理します。saga はエフェクトの説明を返し、saga middleware により実行され、JS アプリケーションの「バックグラウンドスレッド」のように動作します。
適している場合: 複雑な非同期ロジック、分離されたワークフロー
function* fetchData(action) {
const { someValue } = action
try {
const response = yield call(myAjaxLib.post, '/someEndpoint', {
data: someValue
})
yield put({ type: 'REQUEST_SUCCEEDED', payload: response })
} catch (error) {
yield put({ type: 'REQUEST_FAILED', error: error })
}
}
function* addTodosIfAllowed(action) {
const { todoText } = action
const todos = yield select(state => state.todos)
if (todos.length < MAX_TODOS) {
yield put({ type: 'ADD_TODO', text: todoText })
}
}
redux-observable/redux-observable
「エピック」と呼ばれる RxJS observable チェーンを使用して非同期ロジックを処理します。非同期アクションを構成してキャンセルし、副作用などを生成します。
適している場合: 複雑な非同期ロジック、分離されたワークフロー
const loginRequestEpic = action$ =>
action$
.ofType(LOGIN_REQUEST)
.mergeMap(({ payload: { username, password } }) =>
Observable.from(postLogin(username, password))
.map(loginSuccess)
.catch(loginFailure)
)
const loginSuccessfulEpic = action$ =>
action$
.ofType(LOGIN_SUCCESS)
.delay(2000)
.mergeMap(({ payload: { msg } }) => showMessage(msg))
const rootEpic = combineEpics(loginRequestEpic, loginSuccessfulEpic)
Elm アーキテクチャを Redux に移植したもので、レデューサーからエフェクトを返すことで、エフェクトのシーケンスを自然かつ純粋に行うことができます。レデューサーは現在、ステート値と副作用の説明の両方を返します。
適している場合: Redux+JS で Elm にできるだけ近づける場合
export const reducer = (state = {}, action) => {
switch (action.type) {
case ActionType.LOGIN_REQUEST:
const { username, password } = action.payload
return loop(
{ pending: true },
Effect.promise(loginPromise, username, password)
)
case ActionType.LOGIN_SUCCESS:
const { user, msg } = action.payload
return loop(
{ pending: false, user },
Effect.promise(delayMessagePromise, msg, 2000)
)
case ActionType.LOGIN_FAILURE:
return { pending: false, err: action.payload }
default:
return state
}
}
observable を使用して構築された副作用ライブラリですが、コールバック、約束、async/await、または observable の使用を許可します。アクションの宣言的処理を提供します。
適している場合: 非常に分離された非同期ロジック
const loginLogic = createLogic({
type: Actions.LOGIN_REQUEST,
process({ getState, action }, dispatch, done) {
const { username, password } = action.payload
postLogin(username, password)
.then(
({ user, msg }) => {
dispatch(loginSucceeded(user))
setTimeout(() => dispatch(showMessage(msg)), 2000)
},
err => dispatch(loginFailure(err))
)
.then(done)
}
})
プロミス
acdlite/redux-promise
プロミスをアクションのペイロードとしてディスパッチし、プロミスが解決または拒否されると FSA 準拠のアクションがディスパッチされます。
dispatch({ type: 'FETCH_DATA', payload: myAjaxLib.get('/data') })
// will dispatch either {type : "FETCH_DATA", payload : response} if resolved,
// or dispatch {type : "FETCH_DATA", payload : error, error : true} if rejected
lelandrichardson/redux-pack
ユーザーを適切な方向に導きながら dispatch の完全な力を公開しない、常識的な宣言的、慣習に基づいたプロミスの処理。
dispatch({type : "FETCH_DATA", payload : myAjaxLib.get("/data") });
// in a reducer:
case "FETCH_DATA": =
return handle(state, action, {
start: prevState => ({
...prevState,
isLoading: true,
fooError: null
}),
finish: prevState => ({ ...prevState, isLoading: false }),
failure: prevState => ({ ...prevState, fooError: payload }),
success: prevState => ({ ...prevState, foo: payload }),
});
ミドルウェア
ネットワークとソケット
svrcekmichal/redux-axios-middleware
Axios でデータをフェッチし、開始/成功/失敗アクションをディスパッチします
export const loadCategories() => ({ type: 'LOAD', payload: { request : { url: '/categories'} } });
agraboso/redux-api-middleware
API 呼び出しアクションを読み取り、フェッチし、FSA をディスパッチします
const fetchUsers = () => ({
[CALL_API]: {
endpoint: 'http://www.example.com/api/users',
method: 'GET',
types: ['REQUEST', 'SUCCESS', 'FAILURE']
}
})
itaylor/redux-socket.io
socket.io と redux 間の自意識的コネクタ。
const store = configureStore({
reducer,
middleware: getDefaultMiddleware =>
getDefaultMiddleware.concat(socketIoMiddleware)
})
store.dispatch({ type: 'server/hello', data: 'Hello!' })
tiberiuc/redux-react-firebase
Firebase、React、Redux 間の統合
非同期動作
rt2zz/redux-action-buffer
ブレーカー条件が満たされるまですべての action をキューにバッファリングし、その時点でキューが解放されます
wyze/redux-debounce
action に debounce を行う Redux 用の FSA 準拠ミドルウェア。
mathieudutour/redux-queue-offline
オフライン時にアクションをキューに入れて、オンラインに戻ったらディスパッチします。
アナリティクス
rangle/redux-beacon
あらゆるアナリティクスサービスと統合し、オフライン中に追跡でき、アプリロジックからアナリティクスロジックを切り離します
markdalgleish/redux-analytics
メタアナリティクス値を持つ Flux Standard Actions を監視し、それらを処理します
エンティティとコレクション
tommikaikkonen/redux-orm
Redux ストアのリレーショナルデータを管理する単純な不変 ORM。
Versent/redux-crud
CRUD ロジック用の慣習に基づいたアクションとレデューサー
kwelch/entities-reducer
Normalizr からのデータを処理する高階レデューサー。
amplitude/redux-query
コンポーネントで共有されるデータ依存関係を宣言し、コンポーネントのマウント時にクエリを実行し、楽観的な更新を実行し、Redux アクションを使用してサーバーの変更をトリガーします。
cantierecreativo/redux-bees
データを正規化し、クエリを実行できる React HOC を備えた宣言的 JSON-API 相互作用
GetAmbassador/redux-clerk
正規化、楽観的な更新、同期/非同期アクションクリエイター、セレクター、拡張可能なレデューサーによる非同期 CRUD 処理。
shoutem/redux-io
非同期 CRUD、正規化、オプティミスティック更新、キャッシュ、データ ステータス、エラー処理を伴う JSON-API 抽象化
jmeas/redux-resource
リモート サーバーに永続化されたデータを表す「リソース」を管理するための小さな強力なシステム
コンポーネント ステートとカプセル化
threepointone/redux-react-local
コンポーネントのアクションを処理する、Redux のローカル コンポーネント ステート
@local({
ident: 'counter', initial: 0, reducer : (state, action) => action.me ? state + 1 : state }
})
class Counter extends React.Component {
epeli/lean-redux
Redux でのコンポーネント ステートを setState と同じくらい簡単にします
const DynamicCounters = connectLean(
scope: "dynamicCounters",
getInitialState() => ({counterCount : 1}),
addCounter, removeCounter
)(CounterList);
DataDog/redux-doghouse
アクションとリデューサをコンポーネントの特定のインスタンスにスコープすることで、再利用可能なコンポーネントを Redux で簡単に構築することを目指しています
const scopeableActions = new ScopedActionFactory(actionCreators)
const actionCreatorsScopedToA = scopeableActions.scope('a')
actionCreatorsScopedToA.foo('bar') //{ type: SET_FOO, value: 'bar', scopeID: 'a' }
const boundScopeableActions = bindScopedActionFactories(
scopeableActions,
store.dispatch
)
const scopedReducers = scopeReducers(reducers)
Dev ツール
デバッガとビューア
Dan Abramov の元祖 Redux DevTools の実装、アプリ内でのステート表示やタイムトラベルによるデバッグ用に構築
zalmoxisus/redux-devtools-extension
Mihail Diordiev のブラウザ拡張機能。複数のステート モニタビューをバンドルし、ブラウザ自身の dev ツールとの統合を追加
アプリ ステート、API リクエスト、パフォーマンス、エラー、サガ、アクション ディスパッチなど、React および React Native アプリを検査するためのクロスプラットフォームの Electron アプリ
DevTools モニタ
ログ モニタ
ツリー ビューを使用した Redux DevTools のデフォルト モニタ
ドック モニタ
Redux DevTools モニタ用の、サイズ変更と移動が可能なドック
スライダー モニタ
記録された Redux アクションを再生するための Redux DevTools のカスタム モニタ
ディフ モニタ
アクション間の Redux ストア突然変異をディフする Redux DevTools 用のモニタ
フィルタ可能ログ モニタ
Redux DevTools 用のフィルタ可能ツリー ビュー モニタ
フィルター アクション
アクションをフィルタできる、構成可能な Redux DevTools モニタ
ロギング
evgenyrodionov/redux-logger
アクション、ステート、ディフを表示するロギング ミドルウェア
inakianduaga/redux-state-history
タイムトラベルや効率的なアクション レコーディング機能を提供するエンハンサー。アクション ログやアクション再生のインポート/エクスポートを含む
joshwcomeau/redux-vcr
ユーザー セッションをリアルタイムで記録して再生
socialtables/redux-unhandled-action
開発中にステートの変更を生成しなかったアクションに関する警告
突然変異検出
leoasis/redux-immutable-state-invariant
ディスパッチ内またはディスパッチ間でステートを突然変異させようとしたときにエラーをスローするミドルウェア
flexport/mutation-sentinel
ランタイムによる突然変異を深く検出し、コードベースで不変性を適用するのに役立ちます
mmahalwy/redux-pure-connect
不純なプロパティを作成する mapState
が react-redux の connect メソッドに渡されるかどうかを確認してログに記録します
テスト
arnaudbenard/redux-mock-store
アサーション用にディスパッチされたアクションを配列に保存するモック ストア
Workable/redux-test-belt
ストアをアサート、分離、操作しやすくするためにストア API を拡張
conorhastings/redux-test-recorder
アプリのアクションに基づいてリデューサ テストを自動的に生成するミドルウェア
wix/redux-testkit
Redux プロジェクト(リデューサ、セレクタ、アクション、サンク)をテストするための包括的かつ実践的なテストキット
jfairbank/redux-saga-test-plan
サガの統合テストおよびユニット テストを簡単に行えます
ルーティング
supasate/connected-react-router Redux ストアと React Router v4+ の状態を同期させます。
faceyspacey/redux-first-router
完全シームレスな Redux-first ルーティング。アプリは状態として捉えられ、コンポーネントやルートではなく、アドレスバーとの同期を維持します。すべては状態です。コンポーネントを関連付け、フラックス標準アクションをディスパッチするだけです。
フォーム
erikras/redux-form
あらゆる機能を備えたライブラリで、React HTML フォームでステートを Redux に保存できます。
davidkpiano/react-redux-form
React Redux Form はリデューサー作成者とアクション作成者のコレクションで、React と Redux で最も複雑でカスタムなフォームを実装することが簡単かつ効率的になります。
高レベルの抽象化
keajs/kea
Redux、Redux-Saga、Reselect の抽象化。アプリのアクション、リデューサー、セレクター、Saga のフレームワークを提供します。Redux を強化し、setState を使用するのと同じくらい簡単に使用できます。構成と冗長性を削減する一方、構成性を維持しています。
TheComfyChair/redux-scc
定義された構造を取り、「動作」を使用して、アクション、リデューサーの応答、セレクターのセットを作成します。
Bloomca/redux-tiles
Redux 上で作動する最小の抽象化を提供し、簡単な構成、簡単な非同期リクエスト、健全なテスト性を備えています。
コミュニティ慣習
Flux 標準アクション
Flux 標準アクションオブジェクトのためのユーザーフレンドリーな標準
標準的なリデューサー構成
ネストされたリデューサー構成に関する意見のある標準
ダック:Redux リデューサーのバンドル
リデューサー、アクションタイプ、アクションをバンドルするための提案