DRY Redux with Typescript Thunk and Hooks
After a lot of research and refactoring, I manage to reduce a lot of verbose in my React apps. I couldn’t find a DRY recipe online for Redux, Thunk, Typescript and Hooks. Hence, I want to share what I did.
I assume that readers have already knowledge in frameworks mentioned below.
Example App: Counter
When “Sum + 1” or “Sum -1” buttons are clicked, 1 is summed or subtracted to Counter.counterNumber
When “Get Number Fun Fact” is clicked, a fun fact is fetched from http://numbersapi.com/
The Code
Counter
Let’s start with the counter actions:
This is the whole file! No more, no less… Later we will see where the action dispatcher is created.
It’s necessary to define the enums as strings (e.g. SumCounter = “SumCounter”) so that the actions can be seen in the Redux Devtools.
Let’s see how the reducer looks like:
We can see that I didn’t create an interface separated from an initialState constant. With a class, we can have both in one!
This is then how the counter component looks like:
With the Redux hooks, the connect goes away with mapStateToProps, and mapDispatchToProps. The dispatch is also done directly by the buttons.
Store
The Redux store have also some interesting changes:
For every new reducer, it needs to be combined into the rootReducer. Also new classed needs to be added the the rootState. The rest should remain the same. I created also a dispatcher for all actions. It is still type sage using payload: Partial<rootState>
App
The app code remains the same:
Fun Fact
Here we can see how it looks like when we want to use Thunk to fetch data:
Conclusion
With this approach, I managed to have a more DRY code. The redux hooks make possible to reduce the amount of code and still making it type safe.
To see the full code, I created a github repository.
I also created a short explanation on youtube.