InterviewHubPRO
Section Overview
Q124

Question 124 of 445

Part 5: React Redux State Management (101 - 134)

28%
React & Modern Frontend (445 Qs)•Part 5: React Redux State Management (101 - 134)

What is Redux Thunk?

Redux Thunk middleware allows you to write action creators that return a function instead of an action. The thunk can be used to delay the dispatch of an action, or to dispatch only if a certain condition is met. The inner function receives the store methods dispatch() and getState() as parameters.

Practical Code Example

javascript
// Redux Thunk: Middleware allowing action creators to return a function instead of an action object:
export const fetchUser = (id) => async (dispatch, getState) => {
  dispatch({ type: 'FETCH_START' });
  try {
    const res = await api.get(`/users/${id}`);
    dispatch({ type: 'FETCH_SUCCESS', payload: res.data });
  } catch (err) {
    dispatch({ type: 'FETCH_ERROR', payload: err.message });
  }
};