Why I don't use React-Query and tRPC anymore

ByteGrad
12 Feb 202418:58

Summary

TLDRThis video provides an in-depth analysis of using React Query and tRPC in Next.js applications. The creator explains why they no longer use these tools in Next.js, despite acknowledging their usefulness outside of it. The video highlights Next.js's built-in caching capabilities, server components, and server actions, which offer similar benefits to React Query and tRPC while streamlining the development process. It also discusses the trade-offs between these approaches, giving developers a comprehensive understanding of when to use React Query, tRPC, or Next.js's native features. Overall, the video serves as a valuable resource for developers seeking to optimize their Next.js applications.

Takeaways

  • 👍 The author no longer uses React Query or tRPC in Next.js applications, preferring the built-in caching and server-side rendering capabilities of Next.js.
  • 💻 In traditional React apps, React Query is useful for caching and avoiding redundant network requests, but Next.js handles this automatically.
  • 🔄 Next.js aggressively caches data fetched on the server, even persisting through deployments, making React Query unnecessary for server-side data fetching.
  • ⚡ Next.js also caches the rendered output (RSC payload) and has a client-side cache, contributing to its snappy performance.
  • 🔗 The Next.js Link component prefetches pages as they come into the viewport, further enhancing performance.
  • 💼 While React Query may still be useful for client-side fetching in specific cases like infinite scrolling or polling, it's generally not needed in Next.js.
  • 🔐 For type-safe client-server communication in traditional React apps, tRPC is helpful, but in Next.js, server components and server actions provide similar type safety without the need for tRPC.
  • ✍️ Server actions in Next.js are similar to local functions, with TypeScript inferring the return types, providing type safety for server-side mutations.
  • 📂 The author prefers separating server actions into dedicated files, treating them as important functions in the codebase.
  • 🌐 If supporting clients outside Next.js (e.g., React Native) is a requirement, tRPC may still be necessary, as server actions cannot be used outside Next.js.

Q & A

  • Why did the speaker stop using React Query and tRPC in the latest Next.js?

    -The speaker stopped using React Query in Next.js because Next.js comes with built-in caching mechanisms that automatically cache fetch requests and render results. Therefore, React Query's main purpose of caching data is already handled by Next.js. As for tRPC, Next.js introduced server actions, which provide a similar type-safe way of handling client-server communication without the need for tRPC.

  • How does Next.js handle data fetching and caching?

    -Next.js has three main caching mechanisms: 1) It caches the result of individual fetch calls, 2) It caches the render result of server components (RSC payload), and 3) It uses a client-side cache. Additionally, Next.js automatically prefetches data for links when they come into the viewport.

  • What are the benefits of using server actions in Next.js instead of tRPC?

    -Server actions in Next.js provide type-safety, intelligent code suggestions, and automatic type inference for return values, similar to tRPC. However, server actions are integrated with Next.js and do not require additional boilerplate. They also offer progressive enhancement and integration with powerful hooks like useFormStatus and useOptimistic.

  • How do server actions handle client-side validation?

    -Since server actions cannot trust data coming from the client, they need to validate the input data. This can be done using a library like Zod, similar to how validation is handled in tRPC. After validation, the data is properly typed and can be used safely.

  • What is the potential downside of using server actions in Next.js?

    -One downside of server actions is that they cannot be easily used outside of Next.js. If the plan is to support clients outside of Next.js, such as a React Native mobile app, tRPC may be a better choice for handling client-server communication.

  • How does the speaker recommend handling client-side data fetching in Next.js?

    -For client-side data fetching in Next.js, such as in cases like infinite scrolling or polling, the speaker still recommends using React Query since the fetch API is not automatically cached by Next.js.

  • What is the role of the Suspense component in Next.js when it comes to data fetching?

    -In Next.js, the Suspense component is used to wrap the page component that fetches data. The fallback prop of Suspense is used to render a loading spinner while the data is being fetched asynchronously.

  • How does Next.js handle prefetching data for links?

    -Next.js automatically prefetches data for links that come into the viewport when using the Link component. However, this prefetching behavior is only enabled in production mode.

  • What is the speaker's recommendation for mastering the latest React and Next.js?

    -The speaker highly recommends going through their professional React and Next.js course, which starts from scratch and covers building cutting-edge Next.js applications by the end.

  • When would the speaker still consider using React Query and tRPC?

    -The speaker would still use React Query and tRPC in a React Feat app or a Create React App, as the caching and type-safety benefits provided by these libraries are still relevant in those environments.

Outlines

00:00

🔍 Comparing React Query and Next.js for Data Fetching

The video starts by explaining why the speaker no longer uses React Query or tRPC in Next.js applications, even though they are useful tools outside Next.js. Using a React project example, the speaker demonstrates how React Query caches data fetching requests, eliminating unnecessary network requests for previously fetched data. However, in Next.js, the built-in caching mechanisms automatically handle this, making React Query unnecessary for data fetching in Next.js apps.

05:00

⚡ Next.js Built-in Caching and React Server Components

The speaker explains how Next.js has three main caching mechanisms: caching individual fetch calls, caching the render result (React Server Component payload), and a client-side cache. These caching mechanisms, along with the Suspense component for handling loading states and the Link component for prefetching, make Next.js applications highly performant. The speaker demonstrates how clicking through different job items in a Next.js app does not trigger new network requests due to the aggressive caching.

10:01

🔐 Type Safety with tRPC vs. Next.js Server Actions

The video compares the benefits of using tRPC for type-safe client-server communication with the newer Next.js Server Actions feature. While tRPC provides type safety and autocompletion for API endpoints, Next.js Server Actions achieve similar benefits by leveraging TypeScript's inference capabilities. The speaker demonstrates how Server Actions provide type safety for both input and output data, without the need for additional boilerplate. However, one downside of Server Actions is the potential loss of autocomplete when using the more precise 'unknown' type for input validation.

15:03

🛠 Implementing Server Actions in Next.js

The speaker dives into the implementation details of Server Actions in Next.js. Server Actions are defined as functions within a 'server' module, enabling type-safe input validation and handling of mutations on the server side. The video showcases how Server Actions integrate with features like form handling, progressive enhancement, and optimistic UI updates. The speaker also discusses potential workarounds for the autocomplete issue and considerations for supporting clients outside Next.js, where tRPC might be a better choice.

Mindmap

Keywords

💡React Query

React Query is a library for fetching, caching, and updating data in React applications with minimal configuration. It simplifies data fetching and state management by automating the process of caching requests, updating data, and synchronizing server state with the UI. In the video, the speaker discusses replacing traditional data fetching with React Query to efficiently cache data and eliminate unnecessary network requests. This allows for instant data retrieval on subsequent requests for already fetched data, showcasing React Query's ability to optimize data fetching in React-based projects outside of Next.js.

💡tRPC

tRPC stands for Type-Safe Remote Procedure Call. It allows for creating end-to-end type-safe APIs without schemas or code generation. tRPC simplifies client-server communication by ensuring the types of inputs and outputs match between the client and server, eliminating common bugs associated with mismatched data types. In the script, tRPC is mentioned in the context of fetching data and performing mutations in a type-safe manner, contrasting with traditional fetch API usage that lacks type safety, highlighting its utility in scenarios where both client and server sides are controlled by the developer.

💡Next.js

Next.js is a React framework that provides features like server-side rendering and static site generation, which enhance the performance and SEO of web applications. The video discusses Next.js in the context of data fetching and caching mechanisms that differ from traditional React apps. It highlights how Next.js caches fetch requests automatically, leveraging built-in caching and server components to reduce network requests and improve data retrieval efficiency, thus negating the need for React Query in most cases.

💡Caching

Caching refers to the process of storing copies of files or data in a cache, or temporary storage location, so that future requests for that data can be served faster. The speaker explains how React Query and Next.js handle caching differently. React Query provides a mechanism for caching and reusing fetched data to prevent unnecessary network requests. Meanwhile, Next.js automatically caches fetch requests, both on the server and client-side, enhancing performance by reducing the need to refetch data.

💡Data Fetching

Data fetching in web development refers to the process of requesting data from a server and loading it into a web application. The video contrasts traditional data fetching methods using the useEffect hook and fetch API with more advanced techniques offered by React Query and Next.js. It emphasizes the importance of efficient data fetching for optimizing application performance, especially in terms of caching and reducing network requests.

💡useEffect

useEffect is a React hook that allows you to perform side effects in function components, such as data fetching, subscriptions, or manually changing the DOM. The video mentions useEffect in the context of traditional data fetching methods, where it's used alongside the fetch API to retrieve data. However, this approach is criticized for its inefficiency due to the lack of caching, leading to repeated network requests for the same data.

💡Server Components

Server Components in Next.js allow developers to render components on the server without sending the component code to the client, resulting in smaller bundle sizes and faster load times. The video highlights the role of server components in Next.js for data fetching, explaining how they can directly use database libraries like Prisma to fetch data in a type-safe manner, thus reducing the need for additional data fetching libraries or setups.

💡Type Safety

Type safety refers to the prevention of errors in code through the use of a type system that ensures the correct usage of variables, functions, and objects according to their data types. The video discusses type safety in the context of using tRPC for client-server communication and Next.js server components, emphasizing how these tools help maintain type safety by ensuring that the data exchanged between the client and server matches expected types, reducing runtime errors.

💡Server Actions

Server Actions in Next.js are functions that run on the server to handle data mutations like POST, PUT, and DELETE requests. They offer a way to mutate data on the server from client-side events, like form submissions. The video explains how Server Actions provide type safety and do not require remembering endpoint URLs, making them a powerful feature for performing data mutations directly within Next.js applications without needing external libraries like tRPC for type-safe server-client communication.

💡Prisma

Prisma is an open-source database toolkit that simplifies database access and ensures type safety in Node.js and TypeScript applications. In the video, Prisma is mentioned as a tool used within Next.js server components to fetch data directly, illustrating its use for accessing databases in a type-safe manner, which aligns with Next.js's approach to minimizing the need for additional libraries for data fetching and mutations.

Highlights

The speaker explains why they no longer use React Query or tRPC in Next.js applications, as Next.js provides built-in caching and server components that offer similar benefits without the need for these libraries.

In a React application (without Next.js), the speaker would still use React Query for data fetching and caching to avoid unnecessary network requests.

Next.js automatically caches the result of fetch calls, the render result (RSC payload), and has a client-side cache, making it very performant and reducing the need for libraries like React Query.

The speaker demonstrates how Next.js automatically caches fetched data and shows no new network requests for already fetched data, unlike traditional React applications.

With traditional React applications, every click on an item triggers a new network request, as there is no built-in caching mechanism.

In Next.js, the speaker uses the built-in Suspense component with a fallback to show a loading spinner while data is being fetched.

The speaker explains how Next.js also prefetches data for links in the viewport, further improving performance.

For client-side fetching or polling in Next.js, the speaker acknowledges the potential need for React Query, as the built-in caching is for server-side fetching.

The speaker highlights the benefits of tRPC in traditional React applications, including type safety, automatic endpoint handling, and intelligent code suggestions.

In Next.js, the speaker uses server components and an ORM (Prisma) to achieve type safety and avoid remembering API endpoints, similar to the benefits of tRPC.

For mutations (POST, PUT, DELETE) in traditional React applications, the speaker explains the lack of type safety and endpoint intelligence without tRPC.

Next.js introduces Server Actions, which provide type safety, endpoint intelligence, and progressive enhancement for mutations, similar to tRPC.

The speaker demonstrates how Server Actions provide intelligent code suggestions, type safety, and automatic endpoint handling, similar to tRPC.

Server Actions have some downsides, such as losing type safety when using the precise 'unknown' type for input validation and limited usage outside Next.js applications.

The speaker recommends using their professional React and Next.js course to master the latest developments in the field.

Transcripts

play00:00

everyone I've been getting some

play00:01

questions about using react query and

play00:03

trpc in the latest nextjs so I

play00:05

personally do not use react query or

play00:08

trpc anymore and in this video I want to

play00:10

explain why I don't have anything

play00:11

against these tools in principle I think

play00:13

they're still very useful outside nextjs

play00:16

and I also think that the people who

play00:17

build them and maintain them are very

play00:19

talented people let's actually take a

play00:20

look at why I don't use them anymore so

play00:22

I'm going to use this remote Dev project

play00:24

that is from my reacted next escore some

play00:26

of you will recognize it and here we are

play00:28

actually doing some data fetch so let's

play00:30

actually start with react query so the

play00:32

user can search for something and then

play00:33

we get a list of results and the user

play00:35

can click on one of those results to get

play00:37

the detail right so here I clicked on

play00:38

the at security so that's what we see

play00:40

here let me actually zoom in a little

play00:42

bit so you can see here that I can click

play00:44

around and every time I click on one of

play00:46

them we are loading the actual details

play00:49

of that particular job item right very

play00:51

standard very typical situation here I'm

play00:53

using the same image for all of them by

play00:55

the way so don't be confused they are

play00:57

actually different right so you can see

play00:58

the title here is front end devel veler

play01:00

react and the company name at security

play01:02

here the company name is Asen as so you

play01:04

can see we're we're loading the relevant

play01:06

details for the one that we clicked and

play01:07

when I look in the network tab you can

play01:09

also see that whenever I click on one of

play01:11

them there is a new network request so

play01:13

the data is being Fetch and most

play01:15

importantly when I click on one that we

play01:16

already saw there is a new network

play01:18

request all right so how would we

play01:20

implement this well traditionally

play01:21

without react query you would have the

play01:23

typical use effect right so you would

play01:25

use use effect and then you can use the

play01:26

fetch API to actually fetch the relevant

play01:29

uh job item details right based on the

play01:32

ID that we get here we're going to set

play01:34

the loading is to set to true and

play01:36

ultimately we get the data so we store

play01:38

that in state and then here with is

play01:40

loading we're setting that back to false

play01:41

again right this is basically how you

play01:43

learn react initially right so you have

play01:45

use effect and that's how you fetch data

play01:47

the downside of this is now if I click

play01:49

on the first one you can see there is a

play01:51

network request if I click on the second

play01:53

one there is a new network request what

play01:55

happens if I now go back to the first

play01:57

one the one that we just fetched if I

play01:59

click on the first first one there is a

play02:00

new network request there is no caching

play02:02

and when I go back to the second one

play02:04

there is a new network request we see a

play02:06

loading State there is zero caching so

play02:08

literally every time we click on one of

play02:11

them there is a new network request and

play02:13

that is very inefficient right because

play02:15

why are we making a new network request

play02:16

we just requested this information 5

play02:19

seconds ago so that's where react query

play02:21

comes into play so let's actually

play02:22

replace this with react query all right

play02:24

so I have commented this out and I

play02:26

replaced all of that with react query

play02:28

here so with react quer you get the use

play02:30

Query hook and it will give you the data

play02:33

and an is loading flag as well so with

play02:35

react query um there's three arguments

play02:37

here that will specify so this ID is

play02:40

like a caching key the second part is

play02:43

the actual data fetching right so with

play02:44

react query you still have to specify

play02:46

how you want to do the actual data

play02:48

fetching and then how long it should be

play02:49

cached so what's the benefit of doing

play02:51

this well if I now save here and now uh

play02:54

Let me refresh here for a clean slate

play02:56

all right so now we see the first one

play02:57

here what if I click on the second one

play02:59

well it's going to fetch initially it

play03:01

has to fetch the data right but what

play03:03

happens now if we go back to the first

play03:05

one you can see that was instant right

play03:07

if I now click on the second one you can

play03:09

see that's instant there is no loading

play03:11

State now I can click around between

play03:13

these two because they have already been

play03:15

fetched once and react query knows that

play03:18

if it's an ID that it has seen before

play03:21

right which is why we keep track of it

play03:23

in here it can see that when you pass in

play03:25

an ID and it's an ID that we have

play03:27

already fetched for before react query

play03:29

knows uh we already did this data

play03:30

fetching for ID number five let's say so

play03:33

we're not going to run all of this again

play03:35

I'm just going to give you the data from

play03:36

that number five from before so that's

play03:38

called caching and let me show you that

play03:40

in a network tab as well so if I click

play03:42

on the last one here in the list you can

play03:44

see there is a network request here and

play03:45

there's no way around it initially you

play03:47

need to actually fetch the data and now

play03:49

let's say I click on the one uh on top

play03:51

of that so there's another Network

play03:52

request okay it's the first time so

play03:54

you're going to have to get the data but

play03:56

what happens now if we click on the last

play03:58

one again you can can see I clicked

play04:00

there there was no new network request

play04:02

if I click on the one above it you can

play04:05

see there is no new network request I

play04:07

can I can click back and forth between

play04:09

them there are no new network requests

play04:11

because react query caches these job

play04:14

items um when we fetch them now react

play04:17

query can do many other things but I

play04:18

would argue that this was the main

play04:20

reason we were using react query and

play04:22

this is still how I would do it in a

play04:24

react feat app right so remote Dev is a

play04:26

react feat app and in a feat app I would

play04:28

still use re react query all right so

play04:30

that's for feed right nothing really

play04:32

changes for react feed apps or create

play04:35

react app in case you're still using

play04:36

that right so that all states the same

play04:38

now in nextjs I would argue things

play04:40

change a little bit so here I actually

play04:42

converted the same app to uh the nextjs

play04:45

framework so here it's the same app all

play04:47

the same features and you can see when I

play04:49

click on the second one you can see

play04:50

there's a loading indicator there and if

play04:52

I click on the third one there is a

play04:53

loading indicator but what happens now

play04:56

if I click on the second one the one

play04:58

that we just saw that we already fetch

play05:00

the data off you can see it's instant

play05:02

when I click here it's instant right so

play05:04

these first three I already fetched

play05:06

their data so the next time I come back

play05:09

to them I'm there's not going to be a

play05:10

new network request because nextjs

play05:13

actually caches that for me so let me

play05:15

show you how it looks like in nextjs so

play05:17

in nextjs we do not use use effect we

play05:20

can actually make it async and then you

play05:22

can do the data fetching directly here

play05:24

in the component function body and then

play05:26

if you do it like this next as will

play05:28

automatically cash all of this and let

play05:30

me prove that to you in the network tab

play05:31

as well if I go to the second page here

play05:33

let's say I pick the first one here you

play05:35

can see there is an initial Network

play05:37

request if I click on the second one

play05:38

here there is there are actually two

play05:40

Network requests we can ignore that but

play05:41

you can see there is a network request

play05:43

for every click what happens now if I go

play05:44

back to that first one that I just

play05:46

clicked if I click on that one you can

play05:48

see it's instant there is no new network

play05:50

request if I click on the other one you

play05:52

can see it's also instant there is no

play05:54

new network request because nextjs

play05:56

automatically caches your fetch request

play05:59

actually and how do we get the loading

play06:01

State like we got with react query

play06:03

though because if you look here you can

play06:04

see we are still getting this spinner

play06:06

here so how do you get that loading

play06:08

State actually the loading State Works a

play06:09

little bit differently so on the page in

play06:11

a nextjs project so here on the page

play06:14

component here is that component that's

play06:16

actually doing the data fetching I can

play06:18

wrap it in a suspense and then you can

play06:20

specify a fall back so while the async

play06:23

component is suspended right you can see

play06:26

right while this is going on it will

play06:28

render the f back here and this is the

play06:30

component that actually shows a loading

play06:32

spinner right so you can see here there

play06:34

is a spinner in here right make sure you

play06:36

add a key prop to the suspense so that

play06:39

every time the ID changes the suspense

play06:41

is triggered again very common Pitfall

play06:43

actually right so next you ask comes

play06:45

with built-in caching so that's why I

play06:47

don't use react query for data fetching

play06:49

in nextjs right so nextjs is very

play06:51

aggressively cached actually so it will

play06:53

actually automatically cach the result

play06:55

of this fetch call this individual fetch

play06:58

call whatever result of that is it will

play07:00

actually cash that and that's actually

play07:01

the most powerful cache in nextjs this

play07:04

will persist even throughout deployment

play07:07

and nextd S also caches the result of

play07:10

this render right so your server

play07:11

components this is your server component

play07:13

the result of this render is a so-called

play07:16

RSC payload react server component

play07:18

payload so basically the render result

play07:20

the render result itself is also

play07:22

separately cached and there is also a

play07:25

client side cache that nextjs manages

play07:27

for us and that's actually why it's so

play07:29

Snappy here because as I click around it

play07:32

will actually use that client side cache

play07:34

right so it will not make new network

play07:35

requests to the back end because it can

play07:37

see that we're requesting something that

play07:39

has already been requested before right

play07:41

so those are the three main caches in

play07:43

nextjs now if you use the nextjs link

play07:45

component which we actually do use here

play07:48

in that in that list so for every item

play07:50

in that list it's wrapped in this link

play07:52

component where it will actually specify

play07:54

what needs to happen to the URL when you

play07:56

click on it this is actually prefetched

play07:59

so as these links come into the viewport

play08:01

nexts will automatically prefetch that

play08:03

for me behind the scenes so then when

play08:04

you click it there won't even be a

play08:06

loading state it will be instant now

play08:08

here we still get a loading State

play08:10

because I'm in development here so that

play08:12

link component prefetching is only

play08:13

enabled in production mode that's nextjs

play08:16

is very aggressively cached and that's

play08:18

why I don't use react query in nextjs

play08:20

however sometimes you still need to do

play08:22

client side fetching right so there are

play08:23

still some edge cases where you where

play08:25

you actually want to do client side

play08:26

fetching in that case the fetch API for

play08:29

example is not automatically cached

play08:31

right so this is only automatically

play08:32

cached on the server so if you do client

play08:34

side fetching you may still want to use

play08:36

react query and usually that's the case

play08:38

when you want to fetch data after a user

play08:40

action for example infinite scroll right

play08:42

so the user first has to scroll and then

play08:44

you want to fetch data well you may want

play08:46

to look into react query or you want to

play08:47

do things like polling and some other

play08:49

things in that case you may still want

play08:51

to use react query in nextjs but

play08:53

generally I don't use react query in

play08:54

next J all right so what about trpc

play08:56

let's go back to our feat example so TR

play08:59

RPC is for client server communication

play09:01

making that type safe so let's actually

play09:03

go back to this example of fetching data

play09:06

without react query just the traditional

play09:08

way right so we just use use effect here

play09:11

this is how you would do it

play09:12

traditionally you would fetch the data

play09:13

like this now one of the problems with

play09:14

this is when we get data back here if

play09:17

you hover data you can see it is typed

play09:20

as any and we don't want to have anyes

play09:22

in our codebase because any means

play09:24

anything goes typescript should warn me

play09:25

here hey this method does not exist but

play09:28

as you can see because it's as any well

play09:30

you can do anything this is not type

play09:31

safe so the main problem here is you

play09:33

don't have a good type here another

play09:35

problem is of course you need to

play09:36

remember the actual URL of the end point

play09:39

that you're making that request to right

play09:41

so this is not a robust way of

play09:43

communicating with a back end all right

play09:45

so then here I have an example of trpc

play09:47

so you have to do some setup there is a

play09:49

little bit of a boiler plate here but

play09:50

the benefit is now I don't have to

play09:52

remember the end point I can just use

play09:54

trpc I can see what I have available

play09:57

trpc oh I have a job python by ID method

play10:00

on here and what do we want to do with

play10:02

that well I just want to get data that's

play10:04

called a query and actually I need to

play10:05

pass some value to the endpoint if I

play10:08

forget that typescript warns me here so

play10:10

I get a warning here I need to specify

play10:13

an input right if I pass in the wrong

play10:15

input of a number type let's say I even

play10:18

get a warning it should be a string

play10:20

right so I'm just going to pass that ID

play10:21

so I'm getting a job item by its ID now

play10:24

the main benefit here is now when I

play10:25

hover data you can see I'm getting the

play10:28

actual type right so here now I get the

play10:31

actual type so now if I make a mistake

play10:33

on this and I think I can call some

play10:35

method typescript will actually warn me

play10:37

right and I can fix my mistake so now

play10:39

this return value is properly typed and

play10:41

another benefit is of course I don't

play10:43

have to remember the actual URL of the

play10:45

endpoint right so I can just use some

play10:46

trpc object here and tapescript will

play10:49

provide intelligence here to see what I

play10:51

can do with that all right so then let's

play10:52

go back to next JS how do we get those

play10:54

same benefits without using trpc so trpc

play10:58

is for when you control both the client

play11:00

side as well as the server side right so

play11:03

realistically you're not going to do a

play11:04

fetch call to some third party API most

play11:06

of the time typically you're going to

play11:08

get this type of data from your own

play11:10

database and you're going to use an OM

play11:12

right so here for example with Prisma if

play11:14

I get the job item by ID if I now hover

play11:17

the data you can see I already get this

play11:19

correct type and I also don't have to

play11:22

remember some URL right so for getting

play11:24

data I don't need to use trpc to get

play11:27

these benefits server component allow me

play11:29

to use Prisma directly here right so

play11:31

with server components in xjs and your

play11:33

omm you already will get the correct

play11:35

type here right so to get those benefits

play11:37

for getting data you don't need to use

play11:39

trpc all right so that was for getting

play11:41

data now what about mutations right

play11:43

basically your postp put and delete

play11:45

request well if you have some kind of

play11:47

form let's say and when you submit the

play11:49

form you want to add let's say a job

play11:52

item to the database right so what you

play11:53

would do typically before trpc again you

play11:56

had to sort of guess the URL for the

play11:58

endpoint and here you need to pass the

play12:01

actual data but how do you know the

play12:04

specific data or format and here I don't

play12:07

get any intelligence here right I don't

play12:09

get any relevant intelligence here so I

play12:11

don't really know what to pass exactly

play12:13

I'm just kind of guessing here also if I

play12:15

get any return value let's say an error

play12:17

or something like that right so if I get

play12:19

any return value here you don't get this

play12:21

properly typed you're going to get some

play12:23

any type as we saw before all right so

play12:25

what if we want to do the same with trpc

play12:27

well you can use that trpc object so I

play12:29

can use intelligence here to see the

play12:30

options I have here so I don't have to

play12:32

guess the the endpoint URL I can see

play12:35

there is some option to create a job

play12:37

item and I want to do a mutation so I

play12:39

can do M mutate and then here I can pass

play12:41

the data how do I know what data to pass

play12:43

typescript tells me here so the input

play12:45

needs to be an object with a title and

play12:47

description right so here I can see what

play12:49

I need to pass right so description and

play12:51

title if I make a mistake if I make it a

play12:53

number I get a warning here from

play12:55

typescript so you can see all of this is

play12:57

properly typed including any return

play12:59

value I may get if I hover data you can

play13:01

see data is going to be of this

play13:03

particular shape right so with trpc you

play13:05

get that very nice types saave client

play13:06

server communication all right so then

play13:08

why not use trpc in nextjs well nextjs

play13:11

has another major Innovation and maybe

play13:13

this is even the biggest one which is

play13:15

server actions so server actions are

play13:17

meant to mutate data on the server so

play13:20

instead of using the onsubmit event

play13:22

handler you would actually use the

play13:24

action attribute and then here you can

play13:25

invoke a server action so I actually

play13:27

created a server called create job item

play13:30

I actually put that in a separate file

play13:31

we'll take a look at that in a second I

play13:33

could technically also Define it in here

play13:35

if I wanted to but I like to put them in

play13:37

a separate file I can also do uh create

play13:39

job item right I don't have to remember

play13:41

a URL if I don't pass anything

play13:43

typescript will warn me actually right

play13:45

so it expects an argument here I know I

play13:47

need to specify an argument here and

play13:49

then here also you can see I'm getting

play13:51

intelligence here so TP is telling me

play13:53

hey you need to pass description and

play13:54

title right so here I can say title if I

play13:56

make a type mistake again you can see

play13:59

I'm passing a number here I get a

play14:01

warning here right so here you can see

play14:02

type number is incorrect I can fix my

play14:04

mistake right so with server actions I

play14:07

also get that intelligence I don't need

play14:09

to remember some URL endpoint and if

play14:11

this returns anything if we uh get

play14:14

something back here if I hover a result

play14:16

you can see this has been automatically

play14:17

inferred by typescript and so these

play14:19

server actions you can call them from

play14:21

anywhere from the client side server

play14:23

side and so these server actions you can

play14:24

invoke them anywhere and they provide

play14:27

the same benefits and so the server

play14:29

actions are very similar to just normal

play14:31

local functions right and typescript can

play14:33

infer whatever you return from that

play14:35

function it can infer what you are

play14:37

returning and so then here as a result

play14:39

we get that type so let's actually take

play14:40

a look at how we Implement a server

play14:42

action like that so I like to put them

play14:44

in a separate file I don't want to have

play14:45

them lingering around in some components

play14:47

they're very important functions

play14:48

actually so I want to have a dedicated

play14:51

place for them in my code base so with

play14:53

us server at the top of the file every

play14:54

function in here becomes a so-called

play14:56

server action so here I have my server

play14:58

action here I Define the input right so

play15:00

you need to pass a new job item and it

play15:02

should be an object with title and

play15:04

description just like how you would

play15:06

specify normal function with its

play15:08

parameters right so you would give a

play15:09

name for the parameter and then the type

play15:11

and whatever type you specify here that

play15:13

will automatically be uh suggested here

play15:15

when you try to use it right so here we

play15:17

got the intelligence because I have

play15:19

typed this here I didn't need to do

play15:20

anything else since surf actions are

play15:22

basically like post API endpoints next s

play15:25

behind the scenes will actually make a

play15:27

post request to uh the back end and

play15:29

since we cannot trust anything coming

play15:31

from the client we do want to validate

play15:33

that whatever we get here that this is

play15:35

actually of the shape that should be

play15:37

right so if we pass something that's not

play15:38

of the correct shape we are actually

play15:40

returning something here from this

play15:42

function just like you would return

play15:43

something from a normal local function

play15:45

and whatever you return here this is

play15:47

also what you will get here as the type

play15:49

right so types skit will just give you

play15:51

that type right so it could be this type

play15:53

in case there is a validation problem

play15:55

right and then we can do the actual

play15:56

mutation in our database and then with

play15:58

revalidate we can update the UI in the

play16:01

same network request I have other videos

play16:03

and server action so we can't spend too

play16:05

much time on them but you can see that

play16:07

we get the same results here with just

play16:09

using server actions there is no

play16:11

additional boilerplate required to make

play16:13

all of that type safety work server

play16:14

actions also have some additional

play16:16

benefit for example here in forms they

play16:18

provide Progressive enhancement which is

play16:20

a very fancy word but it means that if

play16:22

you just specify the server action like

play16:25

this this will actually work without any

play16:27

JavaScript enabled and if you actually

play16:29

do provide some more code like what we

play16:31

we're doing here and maybe here you also

play16:32

want to have maybe a toast message in

play16:34

case there is an error if you do it like

play16:35

that it will actually need JavaScript

play16:37

but then still this form will be

play16:39

prioritized in hydration and the server

play16:42

actions are also integrated with some

play16:44

powerful hooks like use form status to

play16:46

get a pending State and also use

play16:48

optimistic to get optimistic UI one

play16:50

downside here is I did type it as an

play16:53

object like this realistically like I

play16:55

just said we don't really know what we

play16:57

get here you cannot trust any anything

play16:58

coming from the client and with

play17:00

typescript you do want to be as precise

play17:02

as possible so a more precise type for

play17:04

this input is actually unnown we don't

play17:08

really know what we're going to get this

play17:09

would be a more precise type and then

play17:11

you need to validate it with for example

play17:13

zot which is actually very similar to

play17:14

how you would do it in trpc as well so

play17:16

that doesn't change you would run it

play17:18

through some schema first and then once

play17:20

that is successful uh you would use that

play17:22

variable right so then you would use

play17:24

validated job item. dat. tile. data and

play17:28

then here here you also get the proper

play17:29

type right so after validation you do

play17:31

get the right type here on the backend

play17:33

side now the downside of doing this is

play17:35

now when you use the server action since

play17:37

it's typed as unknown we don't really

play17:39

know what we need to pass here right so

play17:41

now we lose that intelligence so that's

play17:43

one downside if you properly type it you

play17:45

do lose the intelligence now there are

play17:46

some rapper libraries that will fix that

play17:49

so my guess is that we will get some

play17:51

rapper library for Server actions that

play17:53

that will fix some of its downsides now

play17:55

one major downside of server actions

play17:57

that is going to be hard to to fix is

play17:59

that you cannot easily use them outside

play18:01

nextjs so if you also want to support

play18:03

let's say a react native mobile app

play18:05

client you can't use these server

play18:07

actions so if your plan is to support

play18:09

clients outside nextjs you may want to

play18:11

stick to trpc so if you're a little bit

play18:14

confused by now completely normal nextjs

play18:16

has really changed the landscape of web

play18:18

development in my opinion if you want to

play18:19

master latest react and nextjs I highly

play18:22

recommend you go through my professional

play18:23

react and nextjs course in which we

play18:25

start from absolute scratch and by the

play18:27

end we're building some really cutting

play18:29

edge nextjs applications you can find

play18:31

the link in the description so just to

play18:33

sum up this video I would still use

play18:35

react query and trpc in a react feed app

play18:38

for example but in a nextjs application

play18:41

I'm probably not going to use react

play18:42

query or trpc I'm doing some client side

play18:45

data fetching in some Edge case in which

play18:47

case I would use react query or I'm

play18:49

planning on supporting clients outside

play18:51

nextjs in which case I would use trpc

play18:54

for my endpoints thanks for watching

play18:55

this video and I hope to see you the

play18:56

next one bye

Rate This

5.0 / 5 (0 votes)

Related Tags
Web DevelopmentNext.jsReactData FetchingCachingTypeScriptServer ComponentsServer ActionstRPCReact Query