Redux Thunk — When my Function it’s called?

Zaharia Anton
2 min readDec 18, 2020

--

While I was in an interview about my Raffle project, I’ve got a very interesting question that made me research a little more about middlewares.

Raffle project was a Ruby on Rails API for backend and React JS for frontend app.

In one of my components, I had the following code:

A simple mapDispatchToProps function, that was helping me to dispatch the newPost action, which was a fetch request the backend to create a new record.

My interviewer asked me something that blocked me for a couple of minutes.

When the function newPost() it’s called?

I was a bit confused as it looks pretty obvious, as this function was a callback for an onClick event. So my first answer was:

“When the onClick event gets triggered.”

That was not the expected answer so we followed the Redux flow to see where the actual work it’s happening.

onClick event it’s triggered {this.props.newPost}, this callback comes from newPost: (post) => dispatch(newPost(post));

No work yet, as we are just dispatching a newPost action that I was talking earlier.

Without Thunk, the work will happen in the action but now, after the fetch, we are again dispatching something, this time, an object {type: "CREATE_POST", payload: result} .

So where the work happens, as we are always returning plain objects?

The answer is that Thunk executes the code for us, that is why it’s called a middleware, being the bridge between the app and Redux.

It was confusing then, but now after realising that my code is only passing pieces of code and not actually running it, it’s making sense.

I can only be very grateful to my interviewer as I could go deeper into this and learned something new.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet