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
Example with hookuseReducer :
constContainer=()=>{const{ dispatch, useReducer }=useStore()useReducer('books',booksReducer)return<buttononClick={()=>dispatch({space: 'book',type: 'ADD_BOOK'})}>
add book
</button>}Modules 'react' and 'redux' should be installed.
Run NPM command:
npm i @simprl/dynamic-reducer
Or yarn:
yarn add @simprl/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]);},}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]);},}You can use Provider from 'react-redux' or create your own context
constApp=()=>{return<Providerstore={exStore}><Container/></Provider>}const{ dispatch, useReducer }=useStore()useReducer('books',booksReducer)