Skip to content

Repository files navigation

Redux dynamic reducer

Add reducer to the store when component mount and remove reducer from the store when component unmount

For more information read this article: Put a Soul into a React-Redux Project

Usage

Example with hookuseReducer :

constContainer=()=>{const{ dispatch, useReducer }=useStore()useReducer('books',booksReducer)return<buttononClick={()=>dispatch({space: 'book',type: 'ADD_BOOK'})}>
add book
</button>}

Install

Modules 'react' and 'redux' should be installed.

Run NPM command:

npm i @simprl/dynamic-reducer

Or yarn:

yarn add @simprl/dynamic-reducer

Setup

1.a. Create store with dynamic reducer:

import{createStore}from'redux';import{reducerasdynamicReducer}from'@simprl/dynamic-reducer';const{ reducer, addReducer }=dynamicReducer()conststore=createStore(reducer)constexStore={
...store,useReducer: (name,reducer)=>{useEffect(()=>addReducer(name,reducer,store.dispatch),[name,reducer]);},}

1.b. Attach to the static reducers:

If your project has static reducers, you can keep they and add the dynamic reducer to the store with static reducers:

import{createStore,combineReducers}from'redux';import{reducerascreateDynamicReducer}from'@simprl/dynamic-reducer';importreducer1from'./ducks/reducer1';importreducer2from'./ducks/reducer2';const{reducer: dynamic, addReducer }=createDynamicReducer()conststore=createStore(combineReducers({
reducer1,
reducer2,
dynamic,}))constexStore={
...store,useReducer: (name,reducer)=>{useEffect(()=>addReducer(name,reducer,store.dispatch),[name,reducer]);},}

2. Set exStore to context provider

You can use Provider from 'react-redux' or create your own context

Use provider from 'react-redux'

constApp=()=>{return<Providerstore={exStore}><Container/></Provider>}

3. Take hook useReducer from hook useStore

const{ dispatch, useReducer }=useStore()useReducer('books',booksReducer)

About

No description, website, or topics provided.

Resources

Stars

2 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages