What is a thunk and how does it work?
masterA thunk is a middleware that allows you to write action creators that return a function instead of a plain action object. This function receives dispatch and getState as arguments, enabling you to:
- Perform asynchronous logic: Delay a dispatch (e.g., after an API call or timeout).
- Perform conditional dispatch: Check the current state using
getState()before deciding whether to dispatch an action. - Complex synchronous logic: Execute logic that requires access to the store's state or dispatch method.
const INCREMENT_COUNTER = 'INCREMENT_COUNTER'
function increment() {
return { type: INCREMENT_COUNTER }
}
// Example: Async thunk
function incrementAsync() {
return dispatch => {
setTimeout(() => {
dispatch(increment())
}, 1000)
}
}
// Example: Conditional thunk
function incrementIfOdd() {
return (dispatch, getState) => {
const { counter } = getState()
if (counter % 2 === 0) {
return
}
dispatch(increment())
}
}