"Redux Ducks" pattern, redux-toolkit, redux-saga and circular dependencies

24 June 2023
Adopting tools and pattern
react-native

Adding redux-toolkit to my code has reduced the amount of code that needs to be handwritten in my apps.

Not too long ago, I am building a web app for a mobile-first application that I am working on. I realized that I needed a more efficient way to manage my redux code. Initially it started with react-native-web and it worked out okay that I could port my react-native code to my web app, written using Next.js and react.js. Writing a web app with react-native components API was certainly not the end goal of the web app, but just a transition to get the momentum going. Transitioning to using standard web HTML and React components requires some effort, but it turns out to be more productive in building web app, even more when I used tailwindcss to style the components.

Now, when it comes to the state management with redux, I have found a better way to structure the directories (compared to existing ones in my project), using redux-toolkit, and "Redux ducks" pattern. Previously, what needs to be done in 3 files for an action and side effects (1 file for action types, another for reducers, and another for redux-saga side effects) can now be done in 1 file. That significantly reduced the amount of boilerplate code, and fewer mistakes when writing those files.

Just be aware of the potential downside of using the ducks pattern, which is potential circular dependencies in the code, which may lead to undefined imports. The solution highlighted in this blog post is elegant and makes sense.

In the future, I hope there is enough time to put the web and mobile apps codebase under a monorepo.

That's all. Cheers.