What is Redux Thunk and why is it needed?
Redux Thunk is a middleware that lets you write action creators that return a function instead of an action object.
Normally, Redux actions must be plain objects. But what if you want to perform an async operation (like an API call) before dispatching an action?
That's where Redux Thunk comes in.
Example without Thunk:
dispatch({ type: 'FETCH_DATA' });
Example with Thunk:
dispatch((dispatch) => { fetch('/api/data') .then(res => res.json()) .then(data => dispatch({ type: 'FETCH_SUCCESS', payload: data })) .catch(error => dispatch({ type: 'FETCH_ERROR', error })); });
In short:
Redux Thunk enables asynchronous logic inside action creators, allowing you to delay the dispatch of an action or dispatch only under certain conditions.