Home  >  Article  >  Web Front-end  >  When is State Access in Redux Action Creators Right for You?

When is State Access in Redux Action Creators Right for You?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-21 18:45:29245browse

When is State Access in Redux Action Creators Right for You?

Accessing Redux State in Action Creators: Options and Considerations

In Redux, accessing the global store state within action creators can be a contentious topic. Here we'll delve into two approaches for state access in action creators and explore their pros and cons.

Static Approach

import store from '../store';
export function someAction() {
  return {
    type: SOME_ACTION,
    items: store.getState().otherReducer.items,
  }
}

This method directly imports the store, relying on it being a singleton exported from a module. While functional, it's discouraged due to server-rendering limitations, where separate stores are often required per request.

Function Approach

export function someAction() {
  return (dispatch, getState) => {
    const {items} = getState().otherReducer;

    dispatch(anotherAction(items));
  }
}

This approach utilizes Redux Thunk middleware, a recommended technique. Thunk allows action creators to dispatch functions instead of plain action objects, providing access to the dispatch and getState functions. While it requires middleware, it works seamlessly for both client and server-side rendering.

Considerations

  • Redux Creator's Opinion: Dan Abramov discourages state access in action creators, advocating for selective use in specific scenarios like cached data checks or conditional dispatches.
  • Redux Maintainer's Perspective: Mark Erikson believes accessing state in thunks is acceptable and encouraged, acknowledging its intended purpose.

Ultimately, the best approach depends on individual application requirements. Ideally, actions should contain minimal information; however, it's acceptable to use getState in action creators when necessary. Consider the pros and cons of both approaches and choose the one that aligns best with your project.

The above is the detailed content of When is State Access in Redux Action Creators Right for You?. 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