DEV Community

Cover image for Taking a Glimpse of What TRPC IS?
Bhavesh Yadav
Bhavesh Yadav

Posted on • Updated on

Taking a Glimpse of What TRPC IS?

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 greeting to 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.

Getting Started with trpc

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.

Scenarios for Using trpc

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.

Conclusion

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.

Happy Coding!

TRPC Official Docs: https://trpc.io/docs/

Top comments (2)

Collapse
 
dsaga profile image
Dusan Petkovic

Thanks for the write up, would be also good to put a link to the official documentation for TRPC, btw. seams like its very good for smaller projects where both front-end and backend are very tightly coupled or managed by the same team.

Collapse
 
codezera profile image
Bhavesh Yadav

trpc.io/docs/

here you go