15 / 18

15. How do you dispatch a thunk from a React component using hooks?

Dispatching a Thunk from a React Component Using Hooks

In Redux Toolkit, you can dispatch a thunk directly from a React component using the useDispatch hook. Since thunks are functions that return a promise, you can also use async/await or unwrap() to handle their results and errors cleanly.

Steps to Dispatch a Thunk with Hooks
  1. 1

    1. Import useDispatch: Get the dispatch function using the useDispatch hook from react-redux.

  2. 2

    2. Dispatch the Thunk: Call dispatch(yourThunk(args)) inside an event handler or useEffect.

  3. 3

    3. Handle Results with unwrap(): If you need to access the fulfilled value or catch an error, use the thunk’s unwrap() method.

Example: Dispatching a Thunk from a React Component

By combining thunks with React hooks, you can easily trigger asynchronous actions from components while keeping the UI responsive and Redux logic clean.