Home > Web Front-end > JS Tutorial > body text

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

Patricia Arquette
Release: 2024-10-21 18:45:29
Original
325 people have browsed it

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,
  }
}
Copy after login

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));
  }
}
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template