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

ByteGrad
12 Feb 202418:58

Summary

TLDRDans cette vidéo, l'animateur explique pourquoi il n'utilise plus React Query et tRPC avec Next.js, malgré qu'il n'ait rien contre ces outils en principe. Il montre comment React Query permet de mettre en cache les données pour éviter les requêtes réseau redondantes, mais souligne que Next.js gère déjà ce caching de manière efficace. Concernant tRPC, il est utilisé pour assurer une communication client-serveur type-safe, mais Next.js propose des actions de serveur qui offrent les mêmes avantages. L'animateur recommande toujours l'utilisation de React Query et tRPC dans des applications React non-Next.js, mais pour Next.js, il préfère les fonctionnalités natives du framework.

Takeaways

  • 😀 L'auteur a arrêté d'utiliser React Query et tRPC dans Next.js, mais il reconnaît leur utilité en dehors de Next.js.
  • 🔍 React Query est utilisé pour la mise en cache des données pour éviter les requêtes réseau redondantes.
  • 🎯 Avec React Query, il n'y a pas de requête réseau lorsque l'on clique sur un élément qui a déjà été chargé, contrairement à l'utilisation traditionnelle de `useEffect`.
  • 🌐 Next.js offre une mise en cache intégrée qui rend inutile l'utilisation de React Query pour la récupération de données.
  • 🛠️ Dans Next.js, la mise en cache fonctionne automatiquement et persiste même après le déploiement grâce à la mise en cache des résultats des appels de récupération.
  • 📱 Next.js utilise également la pré-extraction avec le composant `Link` pour améliorer les performances de navigation.
  • 💡 tRPC est utilisé pour la communication client-serveur type-safe, offrant une meilleure expérience de développement avec TypeScript.
  • 🛂 tRPC permet de spécifier les types d'entrée et de sortie pour les requêtes et les mutations, réduisant les erreurs et améliorant la maintenance du code.
  • 🚀 Next.js introduit les actions serveur qui offrent une alternative à tRPC pour les mutations de données côté serveur.
  • ⚙️ Les actions serveur sont similaires à des fonctions locales et sont appelées de manière universelle, mais nécessitent une validation des entrées.
  • 🌐 Si l'on envisage de prendre en charge des clients en dehors de Next.js, comme une application mobile React Native, tRPC pourrait être préférable à cause de sa portabilité.

Q & A

  • Pourquoi l'auteur n'utilise-t-il plus React Query ou tRPC dans Next.js?

    -L'auteur mentionne qu'il n'utilise plus React Query ou tRPC dans Next.js car Next.js fournit des fonctionnalités de mise en cache intégrées et des actions de serveur qui rendent ces outils superflus dans la plupart des cas.

  • Quel est l'avantage principal de React Query mentionné dans le script?

    -React Query permet de mettre en cache les données récupérées, évitant ainsi de faire de nouvelles requêtes réseau pour les mêmes données, ce qui améliore l'efficacité et les performances de l'application.

  • Comment Next.js gère-t-il le chargement des données sans React Query?

    -Next.js utilise des fonctions asynchrones dans les composants de page pour charger les données, et met en cache automatiquement les résultats des appels de récupération de données, évitant ainsi les nouvelles requêtes réseau pour les données déjà demandées.

  • Quelle est la différence entre l'utilisation de React Query dans une application React FEAT et dans Next.js?

    -Dans une application React FEAT, React Query est utilisé pour la mise en cache côté client, tandis que dans Next.js, la mise en cache est gérée par le framework lui-même, ce qui rend souvent inutile l'utilisation de React Query.

  • Pourquoi l'auteur pense-t-il que les actions de serveur dans Next.js sont préférables à tRPC pour les mutations de données?

    -Les actions de serveur dans Next.js offrent une communication type-safe entre le client et le serveur, similaire à tRPC, mais avec l'intégration native dans Next.js et sans nécessiter de boulot supplémentaire pour le typage et la validation des données.

  • Quels sont les problèmes que tRPC résout dans les applications React traditionnelles?

    -tRPC permet de faire la communication client-serveur type-safe, évite la nécessité de se souvenir des URL des points de terminaison et fournit des avertissements de TypeScript si les données ne sont pas du type attendu.

  • Quels sont les cas où l'auteur recommande toujours l'utilisation de React Query dans Next.js?

    -L'auteur recommande l'utilisation de React Query dans Next.js pour les cas où il y a besoin de récupération de données côté client après une action de l'utilisateur, comme le défilement infini, ou pour les applications qui nécessitent un soutien pour des clients en dehors de Next.js.

  • Quelle est la fonctionnalité de Next.js qui permet de précharger les données pour les liens avant qu'ils ne soient cliqués?

    -La fonctionnalité de Next.js qui permet de précharger les données est le composant Link, qui précharge les pages associées aux liens en les rendant dans la vue portante.

  • Comment les actions de serveur dans Next.js améliorent-elles l'expérience utilisateur sur les formulaires?

    -Les actions de serveur dans Next.js améliorent l'expérience utilisateur en fournissant une progression vers l'amélioration, ce qui signifie que les formulaires fonctionnent même sans JavaScript activé, et en intégrant des fonctionnalités avancées telles que l'utilisation de l'état de soumission et des UI optimistes.

  • Quel est l'inconvénient principal des actions de serveur mentionné dans le script?

    -L'inconvénient principal des actions de serveur est qu'elles ne peuvent pas être facilement utilisées en dehors de Next.js, ce qui limite leur utilisation si l'on souhaite prendre en charge des clients en dehors de Next.js.

Outlines

00:00

🔍 Introduction au problème de la récupération de données avec React Query et tRPC dans Next.js

Le présentateur explique qu'il ne utilise plus React Query et tRPC dans ses projets Next.js, bien qu'il n'ait rien contre ces outils en soi. Il pense qu'ils sont encore très utiles en dehors de Next.js et qu'il est important de reconnaître le talent des personnes qui les ont créés et les entretiennent. Il propose de passer en revue un projet pour illustrer son point de vue. Le projet en question est un exemple de recherche d'emplois où l'utilisateur peut cliquer sur un poste pour voir les détails. Chaque clic déclenche une nouvelle requête réseau, ce qui est inefficace car les données pourraient être mises en cache. Le présentateur montre comment React Query pourrait résoudre ce problème en mettant en cache les données une fois qu'elles ont été récupérées, évitant ainsi de nouvelles requêtes réseau inutiles.

05:00

🚀 Les avantages de React Query dans les applications React FEAT

Le présentateur compare l'utilisation de React Query avec la méthode traditionnelle d'utilisation de l'API fetch dans une application React FEAT (comme Create React App). Il montre que React Query offre un moyen plus efficace de gérer la récupération de données en mettant en cache les résultats des requêtes, ce qui permet d'éviter les requêtes réseau redondantes. Il illustre cela par un exemple où, après avoir récupéré les détails d'un poste, il est possible de naviguer entre les différents postes sans devoir réeffectuer de nouvelles requêtes. Il souligne que, bien que React Query puisse faire beaucoup plus, la mise en cache est le principal avantage pour lequel il l'utilise dans les applications React FEAT.

10:01

🌐 Adaptation de React Query et tRPC dans le contexte de Next.js

Le présentateur explique que dans Next.js, les choses changent car la mise en cache est gérée différemment. Il montre comment, dans Next.js, on peut effectuer des appels de récupération de données directement dans le corps de la fonction composant sans utiliser useEffect. Next.js met automatiquement en cache les résultats des appels de récupération de données, ce qui rend inutile l'utilisation de React Query pour cette tâche. Il illustre cela en montrant que les données récupérées ne déclenchent pas de nouvelles requêtes réseau lorsqu'elles sont reconsultées. Il mentionne également que Next.js possède plusieurs niveaux de mise en cache, y compris la mise en cache des résultats de rendu des composants serveur et des composants clients.

15:03

🛠️ Quand utiliser React Query et tRPC dans Next.js et quand privilégier les fonctionnalités natives

Le présentateur discute des cas où l'on peut encore avoir besoin d'utiliser React Query dans Next.js, comme pour la récupération de données côté client après une action de l'utilisateur, par exemple le défilement infini. Il mentionne également que tRPC est utile pour la communication client-serveur type-safe, mais que dans Next.js, on peut obtenir les mêmes avantages en utilisant des modèles de données objets (ORM) comme Prisma. Il montre comment, avec des composants serveur et des actions serveur, on peut bénéficier de la même type-sécurité et d'une communication efficace avec le backend sans avoir besoin de tRPC. Il conclut en soulignant que, bien que React Query et tRPC soient des outils puissants, Next.js offre des fonctionnalités natives qui rendent souvent ces outils superflus, en particulier pour la mise en cache et la communication avec le backend.

Mindmap

Keywords

💡React Query

React Query est une bibliothèque qui permet de gérer les données distantes et leur mise en cache de manière efficace dans une application React. Dans la vidéo, l'orateur explique qu'il n'utilise plus React Query avec Next.js, car Next.js offre déjà des fonctionnalités de mise en cache intégrées. Cependant, React Query reste utile dans d'autres contextes, comme les applications React classiques, pour optimiser les appels réseau et éviter les requêtes redondantes.

💡tRPC

tRPC est une bibliothèque qui facilite la communication client-serveur de manière type-safe, en utilisant TypeScript. Dans le script, l'orateur mentionne qu'il n'utilise plus tRPC avec Next.js en raison de l'introduction des actions serveur dans Next.js qui offrent des avantages similaires. Cependant, tRPC est encore utile pour les applications mono-répertoire où le client et le serveur sont contrôlés par le même développeur.

💡Next.js

Next.js est un framework React permettant de créer des applications web avec des fonctionnalités de routage côté serveur et de génération de site statique. La vidéo discute de la manière dont Next.js gère la mise en cache et les appels API, rendant souvent inutile l'utilisation de bibliothèques supplémentaires comme React Query et tRPC.

💡Mise en cache

La mise en cache est un mécanisme permettant de stocker temporairement des données pour une utilisation future, afin d'améliorer les performances et de réduire le trafic réseau. Dans le contexte de la vidéo, la mise en cache est abordée comme une fonctionnalité intégrée à Next.js qui rend la plupart des appels à React Query obsolètes pour le chargement de données.

💡Hooks

Les hooks sont une fonctionnalité introduite dans React qui permet d'utiliser des états et d'autres fonctionnalités de cycle de vie des composants de classe sans écrire de classe. Dans la vidéo, 'useEffect' est mentionné comme un hook utilisé traditionnellement pour gérer les appels API, mais qui est en partie remplacé par les fonctionnalités intégrées de Next.js.

💡API Fetch

L'API Fetch est une API web standard pour récupérer des ressources d'un serveur via des requêtes HTTP. Dans le script, l'utilisation de l'API Fetch est discutée comme une méthode traditionnelle de récupération de données, qui peut être optimisée ou remplacée par des solutions plus avancées telles que React Query ou les actions serveur de Next.js.

💡TypeScript

TypeScript est un super-ensemble de JavaScript qui ajoute des types statiques à votre code. Dans la vidéo, TypeScript est mentionné comme un outil permettant de rendre la communication client-serveur plus sûre et plus prévisible, avec des bibliothèques comme tRPC qui s'appuient sur les types pour fournir une expérience de développement plus robuste.

💡Server Components

Les composants serveur Next.js sont des composants React qui sont rendus côté serveur et peuvent accéder directement à la base de données et aux APIs. Dans le script, les composants serveur sont mentionnés comme une raison supplémentaire pour laquelle les outils tels que React Query et tRPC peuvent devenir moins nécessaires, car ils permettent une gestion efficace des données et des requêtes de manière type-safe.

💡Server Actions

Les actions serveur sont une fonctionnalité de Next.js qui permettent d'exécuter du code sur le serveur en réponse à des événements côté client, comme le soumission d'un formulaire. Dans la vidéo, les actions serveur sont discutées comme une alternative à tRPC pour les mutations de données, offrant des avantages tels que la validation des données et l'intégration avec le cycle de vie des composants React.

💡SSR (Server-Side Rendering)

Le rendu côté serveur est un processus où le HTML d'une page web est généré sur le serveur avant d'être envoyé au client. Dans le contexte de la vidéo, SSR est abordé comme une fonctionnalité clé de Next.js qui permet de créer des applications web rapides et efficaces, en rendant les bibliothèques de gestion des données comme React Query moins essentielles pour certaines tâches.

Highlights

The speaker no longer uses react query or tRPC in Next.js projects.

React query is praised for its caching capabilities outside of Next.js.

tRPC is acknowledged for its type safety in client-server communication.

Next.js has built-in caching that reduces the need for react query.

The speaker demonstrates how react query caches data with useQuery hook.

Next.js automatically caches data fetching, eliminating the need for react query in most cases.

Server components in Next.js provide type safety similar to tRPC without additional setup.

Server actions in Next.js offer a way to mutate data on the server with type safety.

The speaker suggests using react query for client-side data fetching in Next.js.

tRPC may still be relevant for Next.js if planning to support clients outside of it.

Server actions provide progressive enhancement, working even with JavaScript disabled.

The speaker recommends using Next.js server actions over tRPC for mutations within Next.js.

The video includes a demonstration of setting up and using server actions in Next.js.

The speaker discusses the limitations of server actions, such as the loss of type intelligence.

The video concludes with a recommendation for a course on advanced React and Next.js.

A summary of when to use react query and tRPC in different React application scenarios is provided.

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)

Étiquettes Connexes
Next.jsReact QuerytRPCCachingPerformanceDéveloppement WebType-SafetyServer ActionsClient-Side FetchingReact Feat