Accessing Redux State within Action Creators: Pros and Cons
Accessing the Redux store state from within action creators remains a topic of debate in the community.
Approach 1: Importing the Store
import store from '../store'; export const SOME_ACTION = 'SOME_ACTION'; export function someAction() { return { type: SOME_ACTION, items: store.getState().otherReducer.items, } }
While this approach avoids middleware, it relies on the store being a singleton exported from a module. However, server rendering requires separate stores for each request, making this approach impractical.
Approach 2: Using getState
export const SOME_ACTION = 'SOME_ACTION'; export function someAction() { return (dispatch, getState) => { const {items} = getState().otherReducer; dispatch(anotherAction(items)); } }
This approach necessitates the use of Redux Thunk middleware but allows for more flexibility, working seamlessly on both client and server.
Opinions from Redux Contributors
Opinions on this matter vary among Redux contributors:
Conclusion
Ultimately, the decision to access state in action creators depends on the specific needs of an application. If minimal action payload is desired, avoiding getState may be preferable. However, if the use case justifies it, accessing state within thunks provides more flexibility and server-side compatibility.
The above is the detailed content of When Is Accessing Redux State Within Action Creators Justified?. For more information, please follow other related articles on the PHP Chinese website!