Code Generation in React with RTK Query

Steven Lemon
12 min readJul 26, 2023

The last year has seen a lot of talk about AI assistance to help developers write our code — Chat-GPT, GitHub Copilot, etc. However, there’s a much older approach that doesn’t get much attention, but in the right circumstances, can be much more powerful— code generation.

In this article, I want to show how we can use code generation to generate the API layer of a React application. Code generation can create the methods to call our APIs and all types needed for both the requests and responses. As we add more endpoints to our APIs, we simply need to rerun the code generation to generate the code for the new endpoints.

The benefit of using code generation over AI tooling is that it removes dev effort rather than just reducing it. With tools like GitHub Copilot, we still need to review, test, and debug its suggestions. Because the output of code generation is deterministic, we can skip worrying about the API layer at all.

The tool we will use to achieve this is @rtk-query/codegen-openapi. RTK Query is part of Redux Toolkit, a library provided by the Redux team to simplify the usage of Redux and strip out a lot of the boilerplate. Redux is still there under the hood, but with Redux Toolkit providing a simplified abstraction layer over the top. Out of the box, RTK Query integrates our API requests with our Redux state, removing…

--

--

Steven Lemon
Steven Lemon

Written by Steven Lemon

Lead Software Engineer and occasional Scrum Master. Writing about the less technical parts of being a developer.

No responses yet