Skip to Content
Learn
Redux Middleware
Introduction to Thunks

Recall that our overarching goal in this lesson is to give you the tools you need to add asynchronous functionality to your Redux apps. One of the most flexible and popular ways to add asynchronous functionality to Redux involves using thunks. A thunk is a higher-order function that wraps computation we want to perform later. For example, this add function returns a thunk that will perform x+y when called.

const add = (x,y) => { return () => { return x + y; } }

Thunks are helpful because they allow us to bundle up bits of computation we want to delay into packages that can be passed around in code. Consider these two function calls, which rely on the add function above:

const delayedAddition = add(2,2) delayedAddition() // => 4

Note that calling add does not cause the addition to happen – it merely returns a function that will perform the addition when called. To perform the addition, we must called delayedAddition.

Instructions

1.

Consider the function remindMeTo, which we’ve defined for you in the code editor.

What do you think will happen if you run remindMeTo('call mom')? Call console.log(remindMeTo('call mom')) in the code editor to test your suspicion.

2.

Logging remindMeTo('call mom') caused “Remember to call mom!!!” to appear in the console. Now write a function, remindMeLater, that takes a string, task, and returns a thunk that returns the result of calling remindMeTo with the argument task.

3.

Call remindMeLater with a task you need to complete later and store the result in a variable reminder.

4.

What do you think will happen when you call reminder? Test your hunch by calling reminder in your code editor and logging the result to the console.

Folder Icon

Take this course for free

Already have an account?