Home  >  Article  >  Web Front-end  >  When Is Accessing Redux State Within Action Creators Justified?

When Is Accessing Redux State Within Action Creators Justified?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-21 18:47:29603browse

When Is Accessing Redux State Within Action Creators Justified?

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:

  • Dan Abramov discourages accessing state in action creators, arguing that it obscures change history and hinders debugging.
  • Mark Erikson on the other hand encourages the use of getState within thunk action creators, citing its intended purpose.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn