Movatterモバイル変換


[0]ホーム

URL:


Skip to main content

Configuring Your Store

In the"Redux Fundamentals" tutorial, we introduced the fundamental Redux concepts by building an example Todo list app. As part of that, we talked abouthow to create and configure a Redux store.

We will now explore how to customise the store to add extra functionality. We'll start with the source code from"Redux Fundamentals" part 5: UI and React. You can view the source from this stage of the tutorial inthe example app repository on Github, orin your browser via CodeSandbox.

Creating the store

First, let's look at the originalindex.js file in which we created our store:

importReactfrom'react'
import{ render}from'react-dom'
import{Provider}from'react-redux'
import{ createStore}from'redux'
importrootReducerfrom'./reducers'
importAppfrom'./components/App'

const store=createStore(rootReducer)

render(
<Provider store={store}>
<App/>
</Provider>,
document.getElementById('root')
)

In this code, we pass our reducers to the ReduxcreateStore function, which returns astore object. We then pass this object to thereact-reduxProvider component, which is rendered at the top of our component tree.

This ensures that any time we connect to Redux in our app viareact-reduxconnect, the store is available to our components.

Extending Redux functionality

Most apps extend the functionality of their Redux store by adding middleware or store enhancers(note: middleware is common, enhancers are less common). Middleware adds extra functionality to the Reduxdispatch function; enhancers add extra functionality to the Redux store.

We will add two middlewares and one enhancer:

  • Theredux-thunk middleware, which allows simple asynchronous use of dispatch.
  • A middleware which logs dispatched actions and the resulting new state.
  • An enhancer which logs the time taken for the reducers to process each action.

Installredux-thunk

npm install redux-thunk

middleware/logger.js

constlogger=store=>next=>action=>{
console.group(action.type)
console.info('dispatching', action)
let result=next(action)
console.log('next state', store.getState())
console.groupEnd()
return result
}

exportdefault logger

enhancers/monitorReducer.js

constround=number=>Math.round(number*100)/100

constmonitorReducerEnhancer=
createStore=>(reducer, initialState, enhancer)=>{
constmonitoredReducer=(state, action)=>{
const start=performance.now()
const newState=reducer(state, action)
const end=performance.now()
const diff=round(end- start)

console.log('reducer process time:', diff)

return newState
}

returncreateStore(monitoredReducer, initialState, enhancer)
}

exportdefault monitorReducerEnhancer

Let's add these to our existingindex.js.

  • First, we need to importredux-thunk plus ourloggerMiddleware andmonitorReducerEnhancer, plus two extra functions provided by Redux:applyMiddleware andcompose.

  • We then useapplyMiddleware to create a store enhancer which will apply ourloggerMiddleware and thethunk middleware to the store's dispatch function.

  • Next, we usecompose to compose our newmiddlewareEnhancer and ourmonitorReducerEnhancer into one function.

    This is needed because you can only pass one enhancer intocreateStore. To use multiple enhancers, you must first compose them into a single larger enhancer, as shown in this example.

  • Finally, we pass this newcomposedEnhancers function intocreateStore as its third argument.Note: the second argument, which we will ignore, lets you preloaded state into the store.

importReactfrom'react'
import{ render}from'react-dom'
import{Provider}from'react-redux'
import{ applyMiddleware, createStore, compose}from'redux'
import{ thunk}from'redux-thunk'
importrootReducerfrom'./reducers'
importloggerMiddlewarefrom'./middleware/logger'
importmonitorReducerEnhancerfrom'./enhancers/monitorReducer'
importAppfrom'./components/App'

const middlewareEnhancer=applyMiddleware(loggerMiddleware, thunk)
const composedEnhancers=compose(middlewareEnhancer, monitorReducerEnhancer)

const store=createStore(rootReducer,undefined, composedEnhancers)

render(
<Provider store={store}>
<App/>
</Provider>,
document.getElementById('root')
)

Problems with this approach

While this code works, for a typical app it is not ideal.

Most apps use more than one middleware, and each middleware often requires some initial setup. The extra noise added to theindex.js can quickly make it hard to maintain, because the logic is not cleanly organised.

The solution:configureStore

The solution to this problem is to create a newconfigureStore function which encapsulates our store creation logic, which can then be located in its own file to ease extensibility.

The end goal is for ourindex.js to look like this:

importReactfrom'react'
import{ render}from'react-dom'
import{Provider}from'react-redux'
importAppfrom'./components/App'
importconfigureStorefrom'./configureStore'

const store=configureStore()

render(
<Provider store={store}>
<App/>
</Provider>,
document.getElementById('root')
)

All the logic related to configuring the store - including importing reducers, middleware, and enhancers - is handled in a dedicated file.

To achieve this,configureStore function looks like this:

import{ applyMiddleware, compose, createStore}from'redux'
import{ thunk}from'redux-thunk'

importmonitorReducersEnhancerfrom'./enhancers/monitorReducers'
importloggerMiddlewarefrom'./middleware/logger'
importrootReducerfrom'./reducers'

exportdefaultfunctionconfigureStore(preloadedState){
const middlewares=[loggerMiddleware, thunk]
const middlewareEnhancer=applyMiddleware(...middlewares)

const enhancers=[middlewareEnhancer, monitorReducersEnhancer]
const composedEnhancers=compose(...enhancers)

const store=createStore(rootReducer, preloadedState, composedEnhancers)

return store
}

This function follows the same steps outlined above, with some of the logic split out to prepare for extension, which will make it easier to add more in future:

  • Bothmiddlewares andenhancers are defined as arrays, separate from the functions which consume them.

    This allows us to easily add more middleware or enhancers based on different conditions.

    For example, it is common to add some middleware only when in development mode, which is easily achieved by pushing to the middlewares array inside an if statement:

    if(process.env.NODE_ENV==='development'){
    middlewares.push(secretMiddleware)
    }
  • ApreloadedState variable is passed through tocreateStore in case we want to add this later.

This also makes ourcreateStore function easier to reason about - each step is clearly separated, which makes it more obvious what exactly is happening.

Integrating the devtools extension

Another common feature which you may wish to add to your app is theredux-devtools-extension integration.

The extension is a suite of tools which give you absolute control over your Redux store - it allows you to inspect and replay actions, explore your state at different times, dispatch actions directly to the store, and much more.Click here to read more about the available features.

There are several ways to integrate the extension, but we will use the most convenient option.

First, we install the package via npm:

npm install --save-dev redux-devtools-extension

Next, we remove thecompose function which we imported fromredux, and replace it with a newcomposeWithDevTools function imported fromredux-devtools-extension.

The final code looks like this:

import{ applyMiddleware, createStore}from'redux'
import{ thunk}from'redux-thunk'
import{ composeWithDevTools}from'redux-devtools-extension'

importmonitorReducersEnhancerfrom'./enhancers/monitorReducers'
importloggerMiddlewarefrom'./middleware/logger'
importrootReducerfrom'./reducers'

exportdefaultfunctionconfigureStore(preloadedState){
const middlewares=[loggerMiddleware, thunk]
const middlewareEnhancer=applyMiddleware(...middlewares)

const enhancers=[middlewareEnhancer, monitorReducersEnhancer]
const composedEnhancers=composeWithDevTools(...enhancers)

const store=createStore(rootReducer, preloadedState, composedEnhancers)

return store
}

And that's it!

If we now visit our app via a browser with the devtools extension installed, we can explore and debug using a powerful new tool.

Hot reloading

Another powerful tool which can make the development process a lot more intuitive is hot reloading, which means replacing pieces of code without restarting your whole app.

For example, consider what happens when you run your app, interact with it for a while, and then decide to make changes to one of your reducers. Normally, when you make those changes your app will restart, reverting your Redux state to its initial value.

With hot module reloading enabled, only the reducer you changed would be reloaded, allowing you to change your codewithout resetting the state every time. This makes for a much faster development process.

We'll add hot reloading both to our Redux reducers and to our React components.

First, let's add it to ourconfigureStore function:

import{ applyMiddleware, compose, createStore}from'redux'
import{ thunk}from'redux-thunk'

importmonitorReducersEnhancerfrom'./enhancers/monitorReducers'
importloggerMiddlewarefrom'./middleware/logger'
importrootReducerfrom'./reducers'

exportdefaultfunctionconfigureStore(preloadedState){
const middlewares=[loggerMiddleware, thunk]
const middlewareEnhancer=applyMiddleware(...middlewares)

const enhancers=[middlewareEnhancer, monitorReducersEnhancer]
const composedEnhancers=compose(...enhancers)

const store=createStore(rootReducer, preloadedState, composedEnhancers)

if(process.env.NODE_ENV!=='production'&& module.hot){
module.hot.accept('./reducers',()=> store.replaceReducer(rootReducer))
}

return store
}

The new code is wrapped in anif statement, so it only runs when our app is not in production mode, and only if themodule.hot feature is available.

Bundlers like Webpack and Parcel support amodule.hot.accept method to specify which module should be hot reloaded, and what should happen when the module changes. In this case, we're watching the./reducers module, and passing the updatedrootReducer to thestore.replaceReducer method when it changes.

We'll also use the same pattern in ourindex.js to hot reload any changes to our React components:

importReactfrom'react'
import{ render}from'react-dom'
import{Provider}from'react-redux'
importAppfrom'./components/App'
importconfigureStorefrom'./configureStore'

const store=configureStore()

constrenderApp=()=>
render(
<Provider store={store}>
<App/>
</Provider>,
document.getElementById('root')
)

if(process.env.NODE_ENV!=='production'&& module.hot){
module.hot.accept('./components/App', renderApp)
}

renderApp()

The only extra change here is that we have encapsulated our app's rendering into a newrenderApp function, which we now call to re-render the app.

Simplifying Setup with Redux Toolkit

The Redux core library is deliberately unopinionated. It lets you decide how you want to handle everything, like storesetup, what your state contains, and how you want to build your reducers.

This is good in some cases, because it gives you flexibility, but that flexibility isn't always needed. Sometimes wejust want the simplest possible way to get started, with some good default behavior out of the box.

TheRedux Toolkit package is designed to help simplify several common Redux use cases, including store setup.Let's see how it can help improve the store setup process.

Redux Toolkit includes a prebuiltconfigureStore function likethe one shown in the earlier examples.

The fastest way to use is it is to just pass the root reducer function:

import{ configureStore}from'@reduxjs/toolkit'
importrootReducerfrom'./reducers'

const store=configureStore({
reducer: rootReducer
})

exportdefault store

Note that it accepts an object with named parameters, to make it clearer what you're passing in.

By default,configureStore from Redux Toolkit will:

Here's what the hot reloading example might look like using Redux Toolkit:

import{ configureStore}from'@reduxjs/toolkit'

importmonitorReducersEnhancerfrom'./enhancers/monitorReducers'
importloggerMiddlewarefrom'./middleware/logger'
importrootReducerfrom'./reducers'

exportdefaultfunctionconfigureAppStore(preloadedState){
const store=configureStore({
reducer: rootReducer,
middleware:getDefaultMiddleware=>
getDefaultMiddleware().prepend(loggerMiddleware),
preloadedState,
enhancers:[monitorReducersEnhancer]
})

if(process.env.NODE_ENV!=='production'&& module.hot){
module.hot.accept('./reducers',()=> store.replaceReducer(rootReducer))
}

return store
}

That definitely simplifies some of the setup process.

Next Steps

Now that you know how to encapsulate your store configuration to make it easier to maintain, you canlook at the Redux ToolkitconfigureStore API, or take a closer look at some of theextensions available in the Redux ecosystem.


[8]ページ先頭

©2009-2025 Movatter.jp