When it comes to building APIs, we often encounter two popular approaches: REST and GraphQL. However, there's another powerful approach that doesn't get as much attention: trpc. trpc offers features like autocompletion, automatic type safety, and request batching without the need for schemas or code generation.
In the world of REST APIs, the most common way to fetch data within a React application is by using the
fetch API or libraries like Axios.
We typically initiate these requests in a
useEffect hook and update the application state accordingly. However, this approach lacks a strong contract between the frontend and backend.
For instance, if you decide to change the property name from
text on the backend, TypeScript won't throw an error during compilation, but your UI will break. This is where
trpc comes to the rescue.
To get started with trpc, you can create a new project using a tool like npm. Once set up, trpc organizes your codebase into routes and procedures.
Routes act like folders, while procedures are like files containing the actual code. By navigating to the example router, you'll find a "load" procedure with an input object containing a string named "name" and an output object with a string named "greeting".
To call this procedure on the frontend, a special API object is used, and you can access the "load" procedure via the example router. Under the hood, trpc utilizes React Query to handle the requests. One noteworthy feature is that trpc batch multiple requests into a single HTTP request, improving performance.
It's worth mentioning some scenarios where trpc might not be the best fit. If your frontend and backend codebase are not written in TypeScript or if you have separate frontend and backend teams, trpc may not align with your architecture.
In conclusion, trpc provides an elegant solution for building typesafe APIs, offering autocompletion, automatic type safety, and request batching.
Its straightforward setup and seamless integration with React Query make it a valuable tool for frontend development.
TRPC Official Docs: https://trpc.io/docs/