Usage with React
info
- If you're using Next.js, read the Usage with Next.js guide instead.
- In order to infer types from your Node.js backend you should have the frontend & backend in the same monorepo.
Add tRPC to existing React project
Server Side
1. Install dependencies
bash
bash
- Zod: most examples use Zod for input validation and we highly recommended it, though it isn't required. You can use a validation library of your choice (Yup, Superstruct, io-ts, etc). In fact, any object containing a parse,createorvalidateSyncmethod will work.
2. Enable strict mode
If you want to use Zod for input validation, make sure you have enabled strict mode in your tsconfig.json:
json
json
If strict mode is too much, at least enable strictNullChecks:
json
json
3. Implement your appRouter
Follow the Quickstart and read the @trpc/server docs for guidance on this. Once you have your API implemented and listening via HTTP, continue to the next step.
Client Side
tRPC works fine with Create React App!
1. Install dependencies
bash
bash
- @trpc/server: This is a peer dependency of @trpc/clientso you have to install it again!
- Tanstack's React Query: @trpc/react provides a thin wrapper over @tanstack/react-query. It is required as a peer dependency.
2. Create tRPC hooks
Create a set of strongly-typed React hooks from your AppRouter type signature with createReactQueryHooks.
utils/trpc.tstsx
utils/trpc.tstsx
3. Add tRPC providers
In your App.tsx
App.tsxtsx
App.tsxtsx
4. Fetch data
pages/IndexPage.tsxtsx
pages/IndexPage.tsxtsx