Home > Web Front-end > JS Tutorial > How Should Redux Action Creators Access State: From Store or Thunk?

How Should Redux Action Creators Access State: From Store or Thunk?

Barbara Streisand
Release: 2024-10-21 18:48:29
Original
530 people have browsed it

How Should Redux Action Creators Access State: From Store or Thunk?

Accessing Redux State Within Action Creators

Question:

In a Redux application, how can one access the global store state from within an action creator? Are the following approaches appropriate?

Approach 1:

<code class="javascript">import store from '../store';

export const SOME_ACTION = 'SOME_ACTION';
export function someAction() {
  return {
    type: SOME_ACTION,
    items: store.getState().otherReducer.items,
  }
}</code>
Copy after login

Approach 2:

<code class="javascript">export const SOME_ACTION = 'SOME_ACTION';
export function someAction() {
  return (dispatch, getState) => {
    const {items} = getState().otherReducer;

    dispatch(anotherAction(items));
  }
}</code>
Copy after login

Answer:

The acceptability of accessing state within action creators is a topic of debate within the Redux community.

Approach 1:

Accessing state directly via store.getState() is discouraged because it relies on store being a global singleton. On the server, where separate stores may exist per request, this approach is problematic.

Approach 2:

This approach is preferred as it uses Redux Thunk middleware, which allows for asynchronous actions and retrieval of the store state via getState(). Thunk works seamlessly on both the client and server and ensures state access is isolated to the specific action.

Considerations:

  • Redux Creator's Perspective: State access in action creators may obscure change history and is generally discouraged.
  • Redux Maintainer's Perspective: Using getState in thunks is encouraged as it leverages a feature specifically designed for such use cases.

Ultimately, both approaches can yield desired results, but Approach 2 is the recommended best practice for avoiding potential pitfalls and maintaining consistency across environments.

The above is the detailed content of How Should Redux Action Creators Access State: From Store or Thunk?. 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