11 / 18

11. How can you use getState and dispatch inside a thunk?

Using getState and dispatch Inside a Thunk in Redux Toolkit

In Redux Toolkit, thunks have access to both getState and dispatch through the second argument of the payload creator function. These allow you to read the current state or dispatch other actions while performing asynchronous logic inside a thunk.

Ways to Use getState and dispatch
  1. 1

    1. Access getState: Use getState() to retrieve the latest Redux store state and make decisions based on it.

  2. 2

    2. Use dispatch: You can dispatch other thunks or regular actions within the same thunk to manage flow or update the state.

  3. 3

    3. Combine both: Read state values and conditionally trigger actions based on them for advanced control.

Example: Using getState and dispatch Inside a Thunk

Using getState and dispatch together gives you full control over conditional fetching, caching, and orchestrating multiple async actions inside Redux Toolkit thunks.

Difficulty: 6/10
Topics: RTK Thunks, Async State Access, Dispatch in Async Logic

Scenario Questions

0-2 years experience
  1. 1

    How would you write a thunk that fetches a user profile only if it’s not already loaded in the state?

  2. 2

    What happens if you try to call dispatch inside a thunk without importing it from the store? How do you fix it?

2-5 years experience
  1. 1

    A thunk is supposed to update a cart after fetching prices, but sometimes the cart state is stale when you read it with getState — how do you debug this?

  2. 2

    You’re using a thunk to conditionally dispatch two actions based on state, but one action isn’t firing — what could be wrong and how would you trace it?

5-8 years experience
  1. 1

    You have a thunk that calls getState to check user permissions before dispatching an API call — how do you handle race conditions when the user logs out mid-request?

  2. 2

    A team is using getState in thunks to make decisions about which API endpoint to call — what are the performance and testability tradeoffs of this pattern versus moving logic to the component?

8+ years experience
  1. 1

    Your app has hundreds of thunks using getState to make routing decisions — how would you refactor this to avoid tight coupling and improve maintainability across teams?

  2. 2

    You’re migrating from Redux Toolkit to a new state management system — how do you identify and isolate thunks that rely heavily on getState and dispatch for business logic, and what’s your migration strategy?

Follow-up Questions

  • What happens if you call dispatch inside a thunk that’s already running?
  • How would you test a thunk that uses getState?
  • Why not just use selectors instead of getState inside the thunk?