Skip to content
Advertisement

Redux createAsyncThunk vs useEffect hook

I’m familiar with react hooks, and i find it really easy to work with useEffect, thunk is very difficult to deal with, can i just use useEffect & axios and just dispatch the result to the store without using createAsyncThunk? is there any major performance benefit to use it over useEffect?

createAsyncThunk:

JavaScript

useEffect:

JavaScript

Advertisement

Answer

The two setups are essentially similar. You can do the same thing with both approaches.

With the codes exactly as you have them written here, there is a major advantage to the createAsyncThunk approach because it will catch any errors that occur in the API call. It will respond to those errors by dispatching a fetchUserById.rejected action instead of a fetchUserById.fulfilled action. Your reducer doesn’t responded to the rejected case which is fine. The error is still caught. With your useEffect you run the risk of “uncaught error in Promise” errors.

Now of course you can catch the errors on your own. You can also dispatch a pending action at the start of the effect. But once you start doing that, the createAsyncThunk might feel a lot easier by comparison since it automatically dispatches pending, fulfilled, and rejected actions.

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement