I've recently found out about redux toolkit and have some questions about how to handle action and reducer separation with it. Before redux toolkit I had separate folders and files for reducers and actions, but in all of the examples on the redux toolkit tutorial they are keeping their actions/thunks in the same file as their reducer/slice. I will need to use axios and createAsyncThunk (I assume) to access my API. Is it still best to separate actions and reducers in separate folders/files? Would it be better to just use createAsyncThunk and createReducer rather than createSlice? And within createSlice, I still don't entirely understand what extraReducers is for and the difference between that and just reducers. If someone with more familiarity with this library could help, I would appreciate it.
1 Answers
I've also recently started playing with Redux toolkit and I think it's absolutely fantastic, really speeds up react / redux development by taking care of A LOT of boilerplate and follows best practices for organizing your state in a normalized way. And you can get it up and running easily with npx create-react-app my-app --template redux
To answer your question, you don't need to separate your reducer and actions, they can fit in the same file now.
I have been using createSlice to make my reducers, createAsyncThunk to call the APIs, and createEntityAdapter to create all the selectors (depends on having a normalized state which I have started using normalizr for)
The thing which helped me the most is carefully following the Intermediate Tutorial Intermediate Tutorial step by step. Here a typical react-redux app is converted to Redux Toolkit style, you will see original style reducer, actions, etc and how they get converted to use the new APIs / style. At end in the clean up section clean up section:
We now have a bunch of action and reducer files that are no longer being used, so we should delete those to clean up the project. [.........] We can also try completely switching from the "folder-by-type" structure to a "feature folder" structure, by moving all of the component files into the matching feature folders.