What’s a “thunk”?

submited by
Style Pass
2024-12-04 06:30:04

I remember when everyone started talking about using “thunks” in Redux to execute code without blocking the UI. And I remember getting tripped up on the word “thunk”. What’s a “thunk”? Why are we calling it that?

The term “thunk” goes all the way back to ALGOL 60! It’s a play on “think”, because the ALGOL compiler needed to “think” about what sort of subroutines to generate. ALGOL allows passing expressions as arguments to subroutines, not just constants. One way of allowing this is to substitute the expression for another subroutine that evaluates the expression when the original subroutine call happens. This new subroutine is the “thunk” - the result of the “thinking”.

In redux-thunk, thunks are passed as an argument to dispatch, which delays their execution until after the React render cycle. This avoids blocking the UI thread when state updates need to happen. If actions need any async logic like making API calls, thunks are the way to handle it.

Leave a Comment