I just can’t wrap my head around this. I’ve seen some examples of performing async operations inside of Redux, for example fetching data with createAsyncThunk. Why can’t we just implement fetchPosts() in a regular react component? Is it because of the improved reusability of fetchPosts() function if we used redux? If so, why can’t we put that function in a separated/exported module, and import the module whenever we need that function?
2
Answers
Your question more related to the structure of the application than the sync Redux function.
I think it necessary to keep different parts of the application decoupled.
As you may need the
fetchPosts()
function somewhere else, that’s why you want Redux to be the one source of data.I am sure people would explain it in some better words.
This is exactly what
createAsyncThunk
allows you to do, together with letting you deal easily with loading/success/error states. You don’t need to use it if you don’t want to, but most likely you will need to write similar boilerplate for each new case of async fetching.Also, for fetching data specifically, you can use RTK Query instead, which will automatically handle caching (and more) for you.