Тёмный
No video :(

Will React's New Cache Fix Its "Use" Hook? 

Jack Herrington
Подписаться 182 тыс.
Просмотров 48 тыс.
50% 1

Can React 18's new `cache` function save the `use` hook and give us the `use(fetch())` pattern that we didn't ask for and probably won't use instead of react-query or SWR?
Code: github.com/jhe...
👉 I'm a host on the React Round-Up podcast: devchat.tv/pod...
👉 Don't forget to subscribe to this channel for more updates: bit.ly/2E7drfJ
👉 Discord server signup: / discord
👉 VS Code theme and font? Night Wolf [black] and Operator Mono
👉 Terminal Theme and font? oh-my-posh with powerlevel10k_rainbow and SpaceMono NF
0:00 Introduction
1:21 Project Setup
2:50 Using The Use Hook
5:53 Trying Out Cache
8:39 Caching Fetch
10:22 Sharing The Cache
13:46 Bringing In Context
17:12 Architecting Around Cache
18:26 Summing Up
19:26 Outroduction

Опубликовано:

 

16 авг 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 257   
@lukei9772
@lukei9772 Год назад
i love you jack herrington
@Rcls01
@Rcls01 Год назад
That's Jaime Oliver
@tasin5541
@tasin5541 Год назад
I think if use hook implemented the conditional checking like rtk query, that would result in a much cleaner code. We could pass a null value to say don't fetch instead of having to add if blocks there.
@alexandru-gabrielmanea4495
@alexandru-gabrielmanea4495 Год назад
Thanks for always keeping us up to date with this stuff! Regarding the outro question: of course we would like to see you talk about the server side also 👍🏻😂
@The14Some1
@The14Some1 Год назад
@jherr 15:13 in this particular case the standart flow is to reogranize your useUserId like this: const useUserId = () => { const context = useContext(UserIdContext); if (!context) { throw new Error("Put your useUserId inside UserIDContext provider!"); } return context; }
@gabrieldelellis2844
@gabrieldelellis2844 Год назад
I'm interested in seeing this work on the server!
@shivamjhaa
@shivamjhaa Год назад
So nice to hear that this finally landed in React. It'll further help libraries like react-query. At the moment, does React provide a way to invalidate the cache?
@joseandkris
@joseandkris Год назад
I agree, React query and swr are gonna be go to used, but creators of these libraries will have these hooks to use and improve their performance, api, etc... :) So all in all, it's an awesome addition, even if we "users" don't use it to fetch client side.
@maddogshwa
@maddogshwa Год назад
That's exactly what I was thinking. Better primitives for the library maintainers like react-query.
@chathulasampath3257
@chathulasampath3257 Год назад
This is great. But i think, for fetching SWR or React Query is much better as it uses SWR approach.
@marouaniAymen
@marouaniAymen Год назад
I'd use react-query instead, because lot of what it was done is already implemented by this library.
@dealloc
@dealloc Год назад
But use+cache can be used in React Server Components and doesn't need explicitly passing the data through props to hydrate components across SSR boundary. At least as of yet... they're still discussing how to support RSC.
@maddogshwa
@maddogshwa Год назад
@@dealloc "use+cache can be used in React Server Components" I'm just a guy trying to stay current but I thought he had to use "use client" because RSC doesn't support this?
@gbjxc
@gbjxc Год назад
Great video! Very curious to learn more about what the cache invalidation story is, as you say at the end… obviously a great solution for static JSON data, not so great for any data that can become stale during the lifetime of a user’s session in the app. Thanks for your work.
@tonienguix4834
@tonienguix4834 Год назад
yes please server also. you the man, jack!
@Norfeldt
@Norfeldt Год назад
so clear walk-through and thoughts in the wrap-up in the end 👏👌
@yashkhd1100
@yashkhd1100 Год назад
Great job as always..Jack. I recently found ur channel and I must say ur content is very high quality. This is off the topic but it would be nice if you can create one video about how u keep track of all this tech updates.
@waliahmed3035
@waliahmed3035 Год назад
Love it Jack... Please make a video for server side handling too. Your videos are best when it comes to logical problems.
@gm1985ub
@gm1985ub Год назад
Very nice explanation. Like it... I'm using RTK query and conditional call is better, ease and clean. Monorepo with separated store as a package is for me best option. For smaller project cache is solution to go.
@josephizang6187
@josephizang6187 Год назад
Jack, thank you. You are awesome. You have helped me get better with React. This is
@merlinni
@merlinni Год назад
Definitely will be useful to see how it works with server components
@karuresu
@karuresu Год назад
Reselect works really great for memoization. 8:53
@Getfit-us
@Getfit-us Год назад
Love to see the server side fetch!
@karsongrady
@karsongrady Год назад
Thanks, Jack. I would love the server side version of this video.
@gotxe
@gotxe Год назад
Wow, React is turning into a mess, hope this "innovation" with use\cache will be either deprecated or used only by library builders that would decide to support RSC. Anyway, thanks for the video, Jack!
@CanRau
@CanRau Год назад
There’s a cool vscod extension called „multiple cursor case preserve“ which does exactly what the name suggests 🎉
@jherr
@jherr Год назад
I'll check that out.
@thepromisebenard
@thepromisebenard Год назад
Awesome video Jack. I was just wondering the use hook behaved that way. Nice Vscode theme as well, what theme is that?
@DjLeonSKennedy
@DjLeonSKennedy Год назад
would be cool to see how to revalidate the cache
@murphyvanoijen6190
@murphyvanoijen6190 Год назад
Very cool. Would be interesting to see a video that explains how to use this cache mechanism to create complex data (header + children) for preparing a create / update to remote database operation
@electroheadfx
@electroheadfx Год назад
Great server side handling too please. ! :)
@ricardomonge2769
@ricardomonge2769 Год назад
We're in 2023. I can't believe frontend engineers are still struggling to fetch data from an API in a clean way from the browser.
@amans6504
@amans6504 Год назад
We are going in the SSR again. Indeed i just feel that I've wasted so much time in the react ecosystem. I could've done something worthy engineering stuff than just optimizing my fetch calls which still sucks. This react ecosystem is tiring now.
@user-fr1ux1de4t
@user-fr1ux1de4t Год назад
React query
@jameshets6780
@jameshets6780 Год назад
@@amans6504 I feel the same. I wasted so much time in the react ecosystem.
@AndrewLapteff
@AndrewLapteff Год назад
is it uncool?
@victorlongon
@victorlongon Год назад
SSR only in not q solution. It should be the preferred/default approach, but there are many use cases to also do that client side.n
@shin5302
@shin5302 Год назад
Thank you for another premium video.
@Jambajakumba
@Jambajakumba Год назад
Love this new addition to React. I've used useSWR for a while now and I'm super happy with it. If there are minor cases where I would opt for this, I don't see it right now. But great addition. Thank you Jack!!!
@wagnermoreira786
@wagnermoreira786 Год назад
such a nice approach! thanks so much Jack! would this work in plain React or just Next?
@nickytonline
@nickytonline Год назад
Great explainer Jack! Always love your content. 👏🏻
@waliahmed3035
@waliahmed3035 Год назад
After this video, I started searching for SWR tutorials on youtube but there isn't any new ones with NextJS13. Can you please make a video for next13? that would be the best thing...
@rocknthesombrero1651
@rocknthesombrero1651 Год назад
I'd like to see this working on the server.
@bigmistqke
@bigmistqke Год назад
16:13 I have been using the 'multiple cursor case prevent' extension for moments like these.
@hakim6801
@hakim6801 Год назад
Thank U jack soo much for ur explanation and productiv contents
@ricksta8839
@ricksta8839 Год назад
Definitely want to see how it works on the server
@fredheladrienkissie1404
@fredheladrienkissie1404 Год назад
You can use the `useˋ hook in React server components, i think it is a better drop in replacement for async components that don’t work natively with typescript.
@valourus
@valourus Год назад
I didnt know that, thanks im deff going to give that a try 👍
@karuresu
@karuresu Год назад
Thanks for the exploration! There's no better place to catch up with the daily breaking changes in the react community.
@pixelotetm
@pixelotetm Год назад
I get your point in this, we shouldn't have to do the work Lol, react framework should've handled that caching thing in the use hook by default
@VKD007
@VKD007 Год назад
Another Amazing video, I really liked this. I've use Apollo Graphql and it does the same thing out of the box ( Caching ).
@danielsotojaimes3602
@danielsotojaimes3602 Год назад
let'sss see it on the server! 🎩 Great video!
@BoudewijnDanser
@BoudewijnDanser Год назад
Clicked all the buttons. Thanks. Could be interesting if there is a proper way to invalidate the cache.
@reactcoder
@reactcoder Год назад
That's pretty cool ❤
@StingSting844
@StingSting844 Год назад
Thanks for the great video explainer Jack. I was under the opinion that this hook has very little use and would eventually lead to boilerplate. As expected they had to add a cache function for it. What's a bit shocking for me is that every API that they add to react has an affinity for infinite loops. Yet they claim this is the perfect library for managing UI. 😅 So many footguns are introduced after hooks
@chris.dillon
@chris.dillon Год назад
> So many footguns Because it's not declarative but it was supposed to be. It started out not leaking abstractions. 🤐
@spencerbigum1309
@spencerbigum1309 Год назад
Yup do the server version! great video!
@AutisticThinker
@AutisticThinker Год назад
🤯Nice, more content like this!!! 🙂
@kkh0101
@kkh0101 Год назад
this video could have been 5 minutes but this guy keeps making funny jokes that only himself laughs.
@cedwards1080
@cedwards1080 Год назад
Omg thank you for the dark mode !!!!!
@jherr
@jherr Год назад
Next time I'll do it fully. The inspector isn't in dark mode this time.
@johnmarkperocho2590
@johnmarkperocho2590 Год назад
Great job as always, Jack! I've been watching your videos for a while now, and this is my first comment. I have a question: What would happen if the data fetched was changed in real-time by another user? I plan on testing this on my machine when I get the chance, but I was just curious if you had already tested it yourself. Keep up the fantastic work!
@jherr
@jherr Год назад
If it's cached you are always going to get the value from the first time it was fetched. That's why I mentioned that with a SPA you are going to need to figure out some cache invalidation strategy.
@johnmarkperocho2590
@johnmarkperocho2590 Год назад
@@jherr Thanks! I see that make sense.
@VidozMusic
@VidozMusic Год назад
Great video as always, Jack! So if I understand it correctly, 'memo' memoizes based on input props, but 'cache' additionally memoizes the result?
@jherr
@jherr Год назад
Memo is exclusively a way to mark a component as "memoized" based on its input props. Where `cache` is a generic memoization function similar to what you might find in lodash.
@minhpn2253
@minhpn2253 Год назад
I'm very interested in this video. Thanks 🥰
@Cahnisama
@Cahnisama Год назад
18:20 I very much want to see the server side of this
@chris.dillon
@chris.dillon Год назад
To me, any cache has a progression of steps. Writing or setting a key is easy. Then you have to figure out how to refresh or invalidate. This is difficult (the meme). Many times time will be used when time is not really what we want. Then we start thinking in events. Then our app structure doesn't support this evented perspective easily. I need to write this up.
@bigmistqke
@bigmistqke Год назад
I would be interested to read. I m a cache noob and not so much information on, especially in comparison w other web stuff.
@angryayam
@angryayam Год назад
Please make the server use hooks video 🙏
@henriquealmeida348
@henriquealmeida348 Год назад
I don't know or even think that this will be better than React Query.
@JohnnySalami-jo4jh
@JohnnySalami-jo4jh 2 месяца назад
Why did the url with the query param cause an infinite loop but not the url without it?
@christerjohanzzon
@christerjohanzzon Год назад
Very interesting, will try to use this instead.
@raphaelbridi
@raphaelbridi Год назад
If I hit the subscribe button again, I will unsubscribe. Love your videos and thanks for sharing your knowledge! Liked as always!
@jherr
@jherr Год назад
That is true!
@josevsebastian2909
@josevsebastian2909 Год назад
What about cache busting? Does it not have it?
@sirajmussafirr147
@sirajmussafirr147 Год назад
Restart the browser. 😂
@SanderCokart
@SanderCokart Год назад
But when using error handling with error.js like so if (status !== 200 ) { throw new Error('Error fetching organization'); } We get Error not implemented when used in client components
@tthiagolino8
@tthiagolino8 Год назад
Great video as always React has been getting more and more tiresome for a long time by including more and more rules unnecessarily, but now it seems to be including even more exceptions than rules It presents 1000x ways to do something and none of them are satisfactory, in the end it is up to the community to take these tools and transform them into a minimally decent solution It's really exciting that React has gathered around itself creators of fantastic libraries (like the tanstack team for example) but it's really disappointing that it's not possible to create even a toy app satisfactorily using React without having to resort to a third-party library
@jherr
@jherr Год назад
Agreed.
@OnceABustAlwaysABust
@OnceABustAlwaysABust Год назад
Can you name a specific problem? I can totally create a toy app with nothing but React
@jherr
@jherr Год назад
@@OnceABustAlwaysABust IMHO the state management primitives provided by React don't scale well beyond simple applications. The dependency arrays are too easy to get wrong.
@jherr
@jherr Год назад
Also it's unclear what the standard React methodology for fetching data is at this point. Which is why libraries like react-query and swr are so popular. And this use hook is just adding to that confusion. It seems to me like `use` is the promise hook that should have been in the original batch of hooks.
@jonsun174
@jonsun174 Год назад
Because React position itself as a UI library only.
@bartomiejperucki3011
@bartomiejperucki3011 Год назад
use/cache look great! However, if we had to work with dynamically changed data (or user changes his/her first name) the fetch workaround would still return the old value.
@jherr
@jherr Год назад
Correct.
@lucas.codes.tutorials
@lucas.codes.tutorials Год назад
@@jherr could you make a video or a short explaining how you would revalidate the path or tag of that fetch request? Like on demand revalidation, after the user changes its name, for instance...
@avneet12284
@avneet12284 Год назад
Would be super cool to see how this works on the server. But I couldn't understand why we get an infinite loop just by passing a query param. I get the distinction between a function reference and its contents but all that changed was the query param, right? Am I missing something here?
@ellipsoid8
@ellipsoid8 Год назад
As it was told in the video, NextJS replaced native fetch with some "wrapped in cache", so i guess this implementation from NextJS is just work with requests with and w/o query params in different manner.
@dzegarra
@dzegarra Год назад
@@ellipsoid8 That's a good assumption. Is that the reason Jack Herrington?
@kevyyar
@kevyyar Год назад
Things are evolving really fast for a dev who's getting into react. I'm switching to svelte or vuejs
@karuresu
@karuresu Год назад
What's the actual use of "use"? Can it handle plain promises? What does when get other values? Is it some sort of state?
@aquastias
@aquastias Год назад
Not related to the video, can you share the settings & extensions you use in VS Code?
@arish_shah
@arish_shah Год назад
This is really cool. How will it compare against react-query or apollo's normalized cache?
@jherr
@jherr Год назад
Probably under-featured versus those IMHO.
@IAmLesleh
@IAmLesleh Год назад
Judging by this video, it doesn't look like there's any way to invalidate the caches like you can in Tanstack query
@helleye311
@helleye311 Год назад
I'm glad they're making these additions. I'm not 100% sure if this would work, but for lightweight revalidation, in fetchUser you could maybe do something like let func = cache((id:number)=>{...}) const revalidate = ()=>func = cache((id:number)=>{...}) return {func, revalidate} of course you'd probably want to extract the inner function somewhere outside of cache, this could even be a wrapper for any function you want to be able to revalidate. But long story short, this would just invalidate the entire cache, since in revalidate we just reassign the cached function to a new one. React query still seems way better for things, but if you don't want to bring it in for whatever reason, but absolutely need some form of revalidation, this would probably work.
@jherr
@jherr Год назад
I'd go with your plan B, flush the whole cache. Have a cache getter function that would dynamically return the cache. Then another function to flush it and make a new empty cache.
@oscardasilva971
@oscardasilva971 Год назад
I'm done with React creating a hook for everything. We as frontend developers are supposed to focus on Creating beautiful and engaging user experiences, but react is shifting our focus into all these unnecessary bullshit. I think it's time to move to Svelte.
@ndanzzid566
@ndanzzid566 Год назад
Is "cache" essentially similar to or the same as other features in fetching libraries like Redux Toolkit Query?
@MrEnsiferum77
@MrEnsiferum77 Год назад
@Jack Why types are complaining that cache not exists in react module? Is singleton pattern can replace cache function?
@matacharacatos
@matacharacatos Год назад
Is there any way we can do a "cache flush" after certain time?
@jherr
@jherr Год назад
Not unless you write that yourself.
@MrZiyak99
@MrZiyak99 Год назад
i really hope when this is Outta experimental they also make useSwr automatically handle all of this on both client and server. while this is cool i really don't wanna think of how I'll need to handle my fetch requests based on if i call it on the client or server
@NorweskiDrwal
@NorweskiDrwal Год назад
This makes so much sense to me! These new APIs are awesome!
@vakhtangnodadze4802
@vakhtangnodadze4802 Год назад
5:01 Question 1)Home gets rendered 2)A promise and then reference is created 3)use sees this change and sends a request to backend 4)data arrives after some time 5)Home renders the data AND that causes steps to begin from 1? Di I understand the problem correctly? 🤔
@jherr
@jherr Год назад
Yep, pretty much. 5 and 1 are both home re-renders. It's 4 that triggers 1.
@vakhtangnodadze4802
@vakhtangnodadze4802 Год назад
@@jherr What I don't understand is why was that caused after you added the parameters? Why not before?
@jherr
@jherr Год назад
@@vakhtangnodadze4802 Yeah, me too. It's just unstable. It shouldn't have worked the first time. To be fair, the NextJS docs say that use(fetch()) is a feature which is currently not supported. I showed it in the video to make folks aware of that viscerally and to give them some reasonable alternatives with `cache`.
@vakhtangnodadze4802
@vakhtangnodadze4802 Год назад
@@jherr Great. Thank you Jack. Keep up the awesome work!
@rogerscript
@rogerscript Год назад
Great video Jack... you're my hero! Just one question, how can I invalidate the cache because of some mutation or something like that to force the network request again?
@jherr
@jherr Год назад
Yeah, that would be entirely up to you though. You'd need to replace the catch them make the fetch.
@rogerscript
@rogerscript Год назад
Oooohhh got it, well, I will continue using React Query then hehe thank you!
@jherr
@jherr Год назад
@@rogerscript Oh wow, yeah, I would recommend that. Use/cache is nowhere near a replacement for react-query.
@JuanoD_
@JuanoD_ Год назад
I always see this as a harder to *use* SWR. PD: Now make your devtools dark mode, sir.
@axios7776
@axios7776 Год назад
Why not just wrap the promise with useMemo? Is cache redundant?
@griffadev
@griffadev Год назад
When is use and cache actually coming to react without next? I can't find any docs on this
@MichaelScharf
@MichaelScharf Год назад
When is the cache cleaned? Looks like a terrible memory leak. I am using mobx for years and I am pretty surprised how many strange solutions come up all the time that solve parts of the problems that mobx solves "magically"
@jherr
@jherr Год назад
It isn’t cleaned AFAIK unless you clean it.
@jora5483
@jora5483 Год назад
Thanks Jack for the guide. Will this beat memo function in all cases?
@jherr
@jherr Год назад
This does not do what the memo function does. You can't use it as a replacement for it, AFAIK.
@informsharique
@informsharique Год назад
What VS Code theme? BTW great video as always 👍
@tomasb3191
@tomasb3191 Год назад
the react component life cycle is just the wrong abstraction, can we all move on already?
@ozanmuyes
@ozanmuyes Год назад
I still don't get it when people makes requests within a component. Why not to seperate concerns?
@giorgos6576
@giorgos6576 Год назад
I mean why not use useQuery or SWR. These offer more capabilities.
@kassios
@kassios Год назад
My question as well. Looks like a stripped down react-query functionality
@s4ndeep1203
@s4ndeep1203 Год назад
Is there any documentation/link for this 'cache' feature ?
@polioann
@polioann Год назад
Why I don't have 'use' and 'cache' while using the same react and react types version with vite?
@jherr
@jherr Год назад
Got me man.
@iPankBMW
@iPankBMW Год назад
Nice video! But how donwe invalidate this data? Lets say i want this to be cached for 60 seconds and next visit should make fresh fetch.
@jherr
@jherr Год назад
The cache function itself isn't going to handle that. I'd add a function that gives you the current cache function and then replace that cache function every sixty seconds.
@CODE-ze7oe
@CODE-ze7oe Год назад
If we edit User Cache will fetch again?
@jherr
@jherr Год назад
How can you edit it?
@mistersunday_
@mistersunday_ Год назад
That’s very useful 😅
@usamasaleem5624
@usamasaleem5624 Год назад
Yes intrested in cache with graphql
@AnthonyTrimble
@AnthonyTrimble Год назад
Server stuff please :)
@vivekkapoor2537
@vivekkapoor2537 Год назад
If we have big data comes from server will browser slow application because of cached data.
@michaelchen163
@michaelchen163 Год назад
Can you link to where in the documentation cache and use are explained?
@solarspear27
@solarspear27 Год назад
I'll have to start calling you JsWizard at this point. Given your deep knowledge in the JavaScript Ecosystem, I wonder what would be your tools of preference for a social network application and why!? - Thanks in advance
@the-nasim
@the-nasim Год назад
Hi great video. I have a question. What if I want to refetch the cached data? How can I do that?
@jherr
@jherr Год назад
Clear the cache. And if you are using the cached fetch there is a `{ cache: "no-cache" }` option that you can send.
@the-nasim
@the-nasim Год назад
@@jherr Thanks a lot.
@natnaelfekadu5086
@natnaelfekadu5086 Год назад
Hey I was trying to develope a website using next js and redux toolkit but I have no idea how to structure the project at all can make a video on project structure of enterprise level project structure for next , redux toolkit with material UI
@marlonmarcello
@marlonmarcello Год назад
Hey Jack, I can't seem to find docs on cache, how would one go about doing invalidation?
@jherr
@jherr Год назад
beta.nextjs.org/docs/data-fetching/caching It's mostly about the server functionality, and there the fetch is cached and has invalidation controls. But that's server only currently.
@marlonmarcello
@marlonmarcello Год назад
@@jherr ohhh, I see. I was looking for it on the react docs. Thank you!
@vigneshwarrv
@vigneshwarrv Год назад
Wow great walk through on cache functionality. I am really wondering how useful would it be on server side. To be precise, cache returns the same data for same fetch function with same arguments by comparing it's ( value for primitive type and reference for non-primitive type ) right?. what if we send object ( body data ) as an argument. If such object come the component instead of from context , it would still make the fetch calls right?
@jherr
@jherr Год назад
Probably shallow compare on the references. Feel free to try it out and let us know.
@vigneshwarrv
@vigneshwarrv Год назад
@@jherr sure sir
@hasan0770816268
@hasan0770816268 Год назад
I cant find `cache` in React docs! does anyone have a link to its docs?
Далее
Signals For Solid, Qwik And React
28:17
Просмотров 47 тыс.
Mastering React Memo
26:56
Просмотров 134 тыс.
The New Option and Result Types of C#
15:05
Просмотров 54 тыс.
I've been using Redis wrong this whole time...
20:53
Просмотров 351 тыс.
I forced EVERYONE to use Linux
22:59
Просмотров 355 тыс.
3 React Mistakes, 1 App Killer
14:00
Просмотров 114 тыс.
No, Flexbox isn't "good enough"
9:18
Просмотров 34 тыс.
Smarter and Simpler React State
26:46
Просмотров 56 тыс.
The React You Want Is 10X Slower
19:56
Просмотров 34 тыс.