Home > Web Front-end > JS Tutorial > How to Access Redux Store State in Action Creators: Direct vs. Redux Thunk?

How to Access Redux Store State in Action Creators: Direct vs. Redux Thunk?

Linda Hamilton
Release: 2024-10-21 18:50:03
Original
477 people have browsed it

How to Access Redux Store State in Action Creators: Direct vs. Redux Thunk?

Accessing Redux Store State in Action Creators

When creating actions in Redux, you may encounter the need to access the global store state. This article will explore two approaches for achieving this: accessing the state directly via an imported store variable or utilizing a Redux Thunk middleware.

Accessing State Directly

<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

This approach relies on the store being a singleton exported from a module. While technically functional, it is not recommended as it complicates server-side rendering where separate stores are required for each request.

Using Redux Thunk

<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

Using Redux Thunk middleware allows access to the store state via the getState function. This approach is preferred as it works seamlessly in both client and server environments.

Considerations

There are differing opinions on the use of getState in action creators. Some argue that it should be limited to scenarios where cached data is checked or authentication status is verified. Others contend that it is acceptable to use getState in thunks.

Ultimately, the best approach depends on the specific needs of your application. While actions should ideally be concise, there are cases where accessing state directly in action creators may be justified.

The above is the detailed content of How to Access Redux Store State in Action Creators: Direct vs. Redux 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