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

tRPC works fine with Create React App!

1. Install tRPC dependencies

  1. yarn add @trpc/client @trpc/server @trpc/react react-query zod
  • React Query: @trpc/react provides a thin wrapper over react-query. It is required as a peer dependency.
  • Zod: most examples use Zod for input validation, 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, create or validateSync method will work.

2. 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.

3. Create tRPC hooks

Create a set of strongly-typed React hooks from your AppRouter type signature with createReactQueryHooks.

  1. // utils/trpc.ts
  2. import { createReactQueryHooks } from '@trpc/react';
  3. import type { AppRouter } from '../path/to/router.ts';
  4. export const trpc = createReactQueryHooks<AppRouter>();
  5. // => { useQuery: ..., useMutation: ...}

4. Add tRPC providers

In your App.tsx

  1. import React from 'react';
  2. import { useState } from 'react';
  3. import { QueryClient, QueryClientProvider } from 'react-query';
  4. import { trpc } from './utils/trpc';
  5. function App() {
  6. const [queryClient] = useState(() => new QueryClient());
  7. const [trpcClient] = useState(() =>
  8. trpc.createClient({
  9. url: 'http://localhost:5000/trpc',
  10. // optional
  11. headers() {
  12. return {
  13. authorization: getAuthCookie(),
  14. };
  15. },
  16. }),
  17. );
  18. return (
  19. <trpc.Provider client={trpcClient} queryClient={queryClient}>
  20. <QueryClientProvider client={queryClient}>
  21. {/* Your app here */}
  22. </QueryClientProvider>
  23. </trpc.Provider>
  24. );
  25. }

4. Fetch data

  1. import { trpc } from '../utils/trpc';
  2. const IndexPage = () => {
  3. const hello = trpc.useQuery(['hello', { text: 'client' }]);
  4. if (!hello.data) return <div>Loading...</div>;
  5. return (
  6. <div>
  7. <p>{hello.data.greeting}</p>
  8. </div>
  9. );
  10. };
  11. export default IndexPage;