The most important function to write performant next.js apps

Sdílet
Vložit
  • čas přidán 21. 08. 2024
  • Become a YT Members to get extra perks!
    www.youtube.co...
    My Products
    🏗️ WDC StarterKit: wdcstarterkit.com
    📖 ProjectPlannerAI: projectplanner...
    🤖 IconGeneratorAI: icongeneratora...
    Useful Links
    💬 Discord: / discord
    🔔 Newsletter: newsletter.web...
    📁 GitHub: github.com/web...
    📺 Twitch: / webdevcody
    🤖 Website: webdevcody.com
    🐦 Twitter: / webdevcody

Komentáře • 116

  • @WebDevCody
    @WebDevCody  Před měsícem +23

    Said hook, but meant function. Don’t kill me

  • @naughtiousmaximus7853
    @naughtiousmaximus7853 Před měsícem +28

    Good Cody: Uses Bearded Blue theme
    Evil Cody: Doesnt use Bearded Blue theme

    • @WebDevCody
      @WebDevCody  Před měsícem +10

      The maintainer of bearded theme is cookn up my own webdevcody theme with my brand colors 🤣 I’m going to suss it out to see if people hate it or not

    • @daphenomenalz4100
      @daphenomenalz4100 Před měsícem +1

      @@WebDevCody that's great lol

  • @windwardhive7363
    @windwardhive7363 Před měsícem +38

    rsc in the mud. react query ftw

  • @kaansal9523
    @kaansal9523 Před měsícem +3

    Whenever I ask a question like: "When the cache will resets?" You always answer my question in seconds. Thank you for this very important and easy solution.

  • @StaleDegree
    @StaleDegree Před měsícem +13

    Btw for fetch api calls, nextjs natively memoizes the results of the fetch request. So if you make the same fetch request in multiple components in the react tree, you don't need to use the new cache requests. This only applies to the native fetch api. If you are using libraries like axios to fetch or database ORMs then cache is the move like Cody shows.

    • @Vantivify
      @Vantivify Před měsícem +2

      From nextjs 15 it wont be the default behaviour.

    • @daphenomenalz4100
      @daphenomenalz4100 Před měsícem

      Would that be a security issue?

  • @Ivcota
    @Ivcota Před měsícem +2

    straight up "I just know nextjs thumbnail" right here

  • @randohundo9795
    @randohundo9795 Před měsícem +1

    Really useful stuff. Especially when you host your app on a "pay per-request" platform you do not want to have it make 7 requests on a page refresh per user.

  • @hello19286
    @hello19286 Před měsícem +1

    I think it's also important to mention that this is already built in for regular fetches in React. React essentially automatically extends the fetch API and will return the cached fetch requests on a per request basis. This becomes especially important if you are fetching from the database (like you are in this function), because that will not get cached automatically.

    • @WebDevCody
      @WebDevCody  Před měsícem

      Often you can’t use fetch to get data from a database. You usually use a database driver.

    • @Vantivify
      @Vantivify Před měsícem

      How people missunderstand such things. React has nothing to do with fetch. Its behaviour that nextjs introduced and made it default which is sooo wrong. Fortunately they remove it as a default and instead it will be opt in in nextjs 15

    • @hello19286
      @hello19286 Před měsícem

      @@Vantivify You're the one unfortunately misunderstanding. React ALSO extends the fetch API. That is why in the video he is importing from React and not Nextjs. This video is about request memoization which is a React caching layer. You are talking about the nextjs data cache layer, that is what is being turned off in nextjs 15.
      Look up request memoization if you don't believe me.

  • @timekouka
    @timekouka Před měsícem +4

    Currently working aswell on a SaaS starter with some cool functionalities implemented. Strongly feel you when you tell that you'll never finish that boilerplate 😂
    and nice one!!

  • @nasko235679
    @nasko235679 Před měsícem +4

    Question: Aren't those children components client components? How are you even using the validateRequests() function inside them? What I do when using lucia is have a parent server component that checks if the user exists in validateRequests() and if they do I pass it as a prop to the children client components for rendering reasons (log out button, displaying someone's name etc) and if it doesn't exist I simply redirect the user to a login page. I believe that way the function also gets called only once.

    • @WebDevCody
      @WebDevCody  Před měsícem

      Yeah I only run getCurrentUser inside server components and often I’ll show different client components if the user is authenticated or not. Sometimes I’ll pass in the user info into the client components, but I often find it better to just try to conditionally show things in the RSC

    • @nasko235679
      @nasko235679 Před měsícem

      @@WebDevCody If you're doing that why is the request running 6-7 times? Isn't it supposed to run on the initial request of the server component only?

    • @JonathanIngram
      @JonathanIngram Před měsícem

      ​@@nasko235679 I believe it's running 6-7 times because we're looking at the outputted console.log statement from a function, whereas by default Server Components will usually look to memoize duplicate fetch requests instead (i.e. if the same fetch request is called multiple times from different components). So therefore, if your function had to do a lot of heavy calculations immediately after receiving that fetch data, then the cache idea would be a perfect opportunity to use it, to help ensure those calculations are only run once.

  • @JS_Jordan
    @JS_Jordan Před měsícem

    Thanks man! Learned something new

  • @katanaut
    @katanaut Před měsícem +1

    Great content as always. Love this short but informative videos ❤

  • @sinatofangsaz2209
    @sinatofangsaz2209 Před měsícem

    wow this one was super helpful. thanks!

  • @aymenbachiri-yh2hd
    @aymenbachiri-yh2hd Před měsícem

    Thank you so much

  • @szymon7932
    @szymon7932 Před měsícem +3

    What keyboard do you use? It sounds amazing

    • @WebDevCody
      @WebDevCody  Před měsícem +1

      Klack.app

    • @Silver-fh4fb
      @Silver-fh4fb Před měsícem

      Cody did a video on the app czcams.com/video/AJDSZcv27JI/video.html

  • @jfhandfield
    @jfhandfield Před měsícem +1

    Thank you for that Cody. Really helpful. If I understand correctly, pretty new to nextjs deving, since it's caching the info, could it replace a React Context since you don't really need to store the data but just get the cached version of the call ?

    • @WebDevCody
      @WebDevCody  Před měsícem +1

      Cache is specifically for your RSC, context is for your client components. It’s different imo

  • @sameerahmedk
    @sameerahmedk Před měsícem +1

    Thank you for sharing! This shows how important it is to check the # of renders/function calls in react.
    Curious to know if useContext hook can also work (wrapping the overall root in context provider and then using it in components) or no?

    • @aleksandrriazantsev5334
      @aleksandrriazantsev5334 Před měsícem

      Curious as well

    • @JayellsNext
      @JayellsNext Před 22 dny

      See this what I do then recall through middleware for certain pages I’m not sure if it’s right or wrong but I do it 😅

  • @ThiagoVieira91
    @ThiagoVieira91 Před měsícem +1

    Learned something new today. Day improved

  • @null_spacex
    @null_spacex Před měsícem +1

    Lmao that joke at the start

  • @keshavakumar9828
    @keshavakumar9828 Před měsícem

    There is always something to learn from your videos. Thank you !

  • @null_spacex
    @null_spacex Před měsícem +1

    Been going through exactly this with my next.js supabase app

  • @slemchik03
    @slemchik03 Před měsícem

    Awesome video. But do next-auth/clerk cache the session request for me or do I need to do it manually?

  • @shacodes
    @shacodes Před měsícem

    may be create a hook with Context API, that will use same instance

  • @PROJECTJMUSIC
    @PROJECTJMUSIC Před měsícem

    I personally like to fetch the user in the root layout and pass it to React Query as initialData in a context.

  • @myonlylovejesus887
    @myonlylovejesus887 Před měsícem

    wow a new theme. what is the name of this theme? really like the green accent.

  • @JoshIbbotson
    @JoshIbbotson Před měsícem

    Hey Cody, what keyboard do you have? It sounds amazing

  • @agustind
    @agustind Před měsícem +2

    Does anybody know which keyboard is Cody using? it sounds awesome

    • @alaskandonut
      @alaskandonut Před měsícem

      Maybe a custom with linear switches. Maybe tactiles.

    • @h4nto772
      @h4nto772 Před měsícem

      he should be using the macbook keyboard with a software that adds the sound of key press on the recording. he has a video showing it

  • @LucasFariaDev
    @LucasFariaDev Před měsícem +1

    i don't think I was ever first! Learned about this recently on Josh's Comeau course, definitely a good one to keep in mind

  • @asustufa1515
    @asustufa1515 Před měsícem

    Without stained blue it feels weird :D

  • @bijesh619
    @bijesh619 Před měsícem +1

    Which theme? Feels easy to look at.

    • @WebDevCody
      @WebDevCody  Před měsícem +2

      Bearded theme feat web dev Cody. It’s not out yet

    • @bijesh619
      @bijesh619 Před měsícem

      ​@@WebDevCodyohh, nice one.

  • @2006Pk
    @2006Pk Před měsícem

    real chads use trpc + react query

  • @gobeksalata
    @gobeksalata Před měsícem

    but, how does internally cache handles the weakmap to be clear when the request is over? that is the question I wonder how react server components handles that 🤔

  • @codingwithjamal
    @codingwithjamal Před měsícem

    I learned something new, when the video started, I thought you were going to use react context. Do people still use context is apps now days or is it not recommended for using data in our app

    • @WebDevCody
      @WebDevCody  Před měsícem +1

      Context is often still needed for various things. I guess it depends on what you need it for. Often you’ll fetch the initial value in your RSC and populate the context value using it so the client component can use it when it hydrates

    • @codingwithjamal
      @codingwithjamal Před měsícem

      @@WebDevCody makes sense, i see RSC has replaced a lot of the old fetch paradigms

  • @fanush3754
    @fanush3754 Před měsícem

    might be a stupid question but how does this work with server components? After working on a few projects I noticed that the response is usually cached on build time in production and not on refresh. Does this cache function override the default nextjs behavior to revalidate on build time and instead revalidates on user request, for instance a Ctrl + R?

    • @WebDevCody
      @WebDevCody  Před měsícem

      If you’re on a page that uses a cookie the page will always be dynamic

  • @devaccess
    @devaccess Před měsícem

    Thank you so much Cody,
    Please which extension are you using for your error to show directly on the editot?

  • @amershboul9107
    @amershboul9107 Před měsícem

    🐐

  • @roberth8737
    @roberth8737 Před měsícem

    Is this something that needs to be done with Clerk as well - or is it just next auth Lucia thing?

    • @WebDevCody
      @WebDevCody  Před měsícem

      No clue, you’d need to check their docs or look to see if they call cache somewhere

  • @ajzack983
    @ajzack983 Před měsícem

    forgive my next.js react ignorance but:
    for how long does the cache holds ?
    from what I understood the cache holds until a full page relaod happens ?
    in this case why not just call the function once and put it in a global frontend state store ?

    • @WebDevCody
      @WebDevCody  Před měsícem +1

      Idk how to answer this honestly. The cache is per request. Sometimes you need to verify values on each request on your backend. Sometimes different RSC in your tree might need the same data during your SSR, so you’d cache it server side

    • @hello19286
      @hello19286 Před měsícem

      This is a different level of cache, this cache (request memoization) get evicted after the request ends. NextJS has 4 levels of caching, I know, extra confusing. You are talking about the Data cache.

    • @ajzack983
      @ajzack983 Před měsícem

      ​@@hello19286I understand but I'm asking about this specific use case since we know probably the user data won't change unless maybe u change your profile or do certain actions then you refresh the user data by fetching the user again.
      Isn't this a common practice among next.js devs to have a front end state store for such use cases ?
      Fetch once, share anywhere and refresh on need.

  • @dejeandev
    @dejeandev Před měsícem

    kind of hard to imagine why this problem would exist in the first place

  • @andresgutgon
    @andresgutgon Před měsícem

    So I 'm using middleware with next-auth and jwt strategy to avoid calling db because you can't unless db is serveless. i guess with react cache i can avoid middleware and use db sessions right?

    • @WebDevCody
      @WebDevCody  Před měsícem

      Yes, it’s hard to answer this question. You cant connect to a database from your middleware because it requires serverless compatible libraries. Many database drivers are not serverless friendly, such as a postgres driver. This means that you either need to expose an api endpoint on your app and do a fetch request from your middleware to your api (which is slow and defeats the purpose of middleware running on edge), or you need to find a driver that will work (or find a way to expose your database over https publically which I’d say is a security concern). My personal opinion is to not use middleware because of added complexity and to just verify sessions on your RSC directly.

  • @tatsumii1420
    @tatsumii1420 Před měsícem

    whats the diffrence between unstable_cache and cache?

  • @r-i-ch
    @r-i-ch Před měsícem

    Wouldn't this be a client-only concern instead of something on the server?

  • @kal.leroux
    @kal.leroux Před měsícem

    how about moving things so that doesn't need to be send over rsc to client component like the button leave so if there is issue (or security issue) with the cache fct that react core team is giving us it won't affect us (I think rsc are good for small peoject but for larger project I prefer having front and backend separated so it easiest to keep track of bug and to separate concern)

    • @WebDevCody
      @WebDevCody  Před měsícem +1

      All my buttons and forms are always client components. I’m not sure I understand what you’re asking

    • @kal.leroux
      @kal.leroux Před měsícem

      @@WebDevCody if it's client side just make a context and all your client component check from the context

  • @yuniorchavez8052
    @yuniorchavez8052 Před měsícem

    how do you revalidate the cached data if you update for example the avatar of your profile, without refreshing the entire page

    • @WebDevCody
      @WebDevCody  Před měsícem

      RevalidatePath or revalidateTag but those are unrelated to what I just discussed

  • @GaurangRShah
    @GaurangRShah Před měsícem

    Someone got a clickety-clack keyboard, didn’t they?

  • @grandpaonfire6834
    @grandpaonfire6834 Před měsícem

    can you not just call getcurrentuser from root and then pass the value with the context api?

    • @WebDevCody
      @WebDevCody  Před měsícem

      You can’t access context values in RSC, but yes you could pass it down as props if you want

  • @cod-the-creator
    @cod-the-creator Před měsícem

    I've always put that kind of stuff in global store and only do the request if the information is missing (essentially the first time the app loads). Is this not a good practice?

    • @WebDevCody
      @WebDevCody  Před měsícem

      I mean, you should really be checking and validating the users, tokens or sessions every single request. For example, if someone invokes your server action, you need to make sure that the Paul request has a valid non-expired session so you can’t really trust that any other way, other than the look it up every time.

  • @dailynews7822
    @dailynews7822 Před měsícem

    What theme you use in VS code ?

  • @sedatdogan6057
    @sedatdogan6057 Před měsícem

    What is this theme name ? i loved

  • @mohammadzaidbhati4663
    @mohammadzaidbhati4663 Před měsícem

    what about next auth where can i add react cache to make it efficient

  • @z-aru
    @z-aru Před měsícem

    So cache is like useMemo but on the server?

  • @legoEgoJJproduction
    @legoEgoJJproduction Před měsícem

    This would be 100% easier to watch if there wasn’t loud af typing

  • @josippardon8933
    @josippardon8933 Před měsícem

    This is cache method is not cacheing at all.
    It does request deduplication acctualy.
    If multiple compoments call this func at same time, it Will be executed only once and its return value Will be forwarded to every place where it was called.
    But yea, nothing is "cached" (saved for later)

    • @WebDevCody
      @WebDevCody  Před měsícem +1

      Take that up with the react team 😉

  • @SeibertSwirl
    @SeibertSwirl Před měsícem

    Good job love!!! First!!

    • @WebDevCody
      @WebDevCody  Před měsícem +3

      You’ll get your reward later tonight

    • @ziaahmad8738
      @ziaahmad8738 Před měsícem +3

      @@WebDevCody woah

    • @ezwa
      @ezwa Před měsícem +2

      i was not expecting this when trying to learn react

    • @Innesb
      @Innesb Před měsícem +3

      @@WebDevCodyAwww! Cuddles and a cup of cocoa later tonight.

    • @WebDevCody
      @WebDevCody  Před měsícem +2

      @@Innesb 🤣

  • @safarl45
    @safarl45 Před měsícem +5

    Next.js sucks! Use remix!!!

    • @emmanuelezeagwula7436
      @emmanuelezeagwula7436 Před měsícem +1

      It will implement RSC very soon so it doesn't change anything to be honest

  • @ListonFermi
    @ListonFermi Před měsícem

    I use node js as backend.
    I get the similar multiple calls to verify jwt when a page loads. (So, I did the verify jwt in that middleware itself, want to know if it's a good practice .)
    I tried the cache in the middleware.ts
    const verifyToken = cache(
    async (tokenName: string, req: NextRequest): Promise => {
    ///logic
    });
    It's throwing this error
    TypeError: (0 , react__WEBPACK_IMPORTED_MODULE_2__.cache) is not a function

    • @WebDevCody
      @WebDevCody  Před měsícem +1

      Verifying the jwt in the middleware is also fine. You shouldn’t need to call cache in the middleware. If the token is invalid just redirect the user to another page. I think you’d still need to call a method to get the user session inside your RSC.

  • @NizzyABI
    @NizzyABI Před měsícem