I Cannot Believe React Made A Hook For This

Поділитися
Вставка
  • Опубліковано 11 жов 2024

КОМЕНТАРІ • 144

  • @MoinKhan_10
    @MoinKhan_10 Рік тому +198

    A brand new video from kyle. A brand new todo application

    • @snivels
      @snivels Рік тому +7

      I wish someone would make something else for once. Anything else.

    • @steinkuste3492
      @steinkuste3492 Рік тому +3

      💀💀💀💀💀😭😭😭😭😭

    • @NicholasShanks
      @NicholasShanks Рік тому +1

      Just what I’ve always wanted.

    • @ricko13
      @ricko13 Рік тому +12

      ​@@snivelslike what? a counter? 😂

    • @big-jo89
      @big-jo89 Рік тому +5

      he just wants to explain the hook with the simplest way possible.

  • @EvertJunior
    @EvertJunior Рік тому +39

    I’m loving how you’re covering upcoming react features. Thank you!

  • @gasparsigma
    @gasparsigma Рік тому +10

    I've been using it with react-query for a couple of years now. Glad to see it becoming native but I'm not super excited about the syntax/API

  • @SurajSingh-fg6eq
    @SurajSingh-fg6eq Рік тому +4

    Love this man! Soft voice with clean explanation

  • @leodevbro
    @leodevbro Рік тому +15

    5:03 - question: if optimistic new item and server new item has different ids, then, when the server item finally comes to the client, how the hook knows which item to check (merge) in the optimistic array? Yeah, it may knows the index in the array, but there can be some situations when index is very dynamic.

    • @y7o4ka
      @y7o4ka Рік тому +13

      setTodos probably just overwrites the optimistic state. So if you update opt state two times then the server adds only one normal todo the second one disappears until we get it from the server.
      This just sounds impractical, so there must be a better mechanism involved, however i can't think of a way from the get-go

    • @elina6969
      @elina6969 Рік тому +1

      I'm wondering the same thing too. How does it know what value needs to be replaced? What if the user creates multiple todos before the server responds (common case in a messaging application where someone could be sending messaging quickly)? What will get replaced? How is the equality checked? It can't be referencial equality because the object that is returned by the server and the optimistic update will never be the same. This video is a good overview but not so much a good explainer

    • @tnfAngel
      @tnfAngel 11 місяців тому +2

      Just use a nonce field, generate the nonce field (not the actual id) in the frontend, send it to the server and make the server return the nonce and the real id, then update the pending item based on the nonce stored in the frontend

  • @bogdanfilimon2486
    @bogdanfilimon2486 Рік тому +16

    Absolutely amazing, the react team (vercel / next) is implementing all the features from Remix lol …

    • @gasparsigma
      @gasparsigma Рік тому

      From react-query :)

    • @kinxori
      @kinxori Рік тому +1

      True!! I've been learning Remix and the fact that I don't even have to face these issues makes me thankful for Remix and the team behind it 🙌

  • @AzaroPk
    @AzaroPk Рік тому +3

    So good! Cant wait for it to become available in stable react version.

  • @dave6012
    @dave6012 Рік тому +3

    As with all these “exciting new updates coming to react” I’ll believe it when they ship it. I’ve already been burned by the other DX improvements that never made it past experimental.
    That said, this is an excellent enhancement and well demonstrated by Kyle!

  • @doc8527
    @doc8527 Рік тому +32

    Optimistic update is an extremely hard problem not just for React, not just for web, but for any frontend applications in general.
    The complexity comes from data validation, data inconsistency between backend and frontend,
    what happens when multiple transactions back and forth in between?
    what happens to the order of those transactions?
    How do we ensure the correctness of transaction order?
    How are we going to fallback if something wrong?
    How to handle diff errors?
    How to notify user without distraction?
    How to handle network disconnection with valid data?
    How to store the temporary local data?
    How to merge those data from multiple places (application-wise, machine-wise)?
    How to we approach the eventual consistency?
    It's a combination problem of code, UI and UX.
    In general you might need this kind of behavior for interaction heavy application, like Google Sheet, Doc, Figma.
    Not your daily todo app, nor the stupid "silent fail" comment section (but unfortunately they were all implemented nowadays, such as UA-cam comment section). Those not suitable cases (like youtube comment sections) causes infamous problem of "the UA-camr deleted my comment" and tons of unnecessary conficts between content creator and audience.

    • @alexradu1921
      @alexradu1921 Рік тому +3

      Yea somehow i think (for the scenarios of todos and comments/likes etc you mentioned) is easier to just have a loading spinning icon until the request has finally succeeded

    • @rubenverster250
      @rubenverster250 Рік тому

      @@alexradu1921 we've clearly been in this too long XD
      Loading state and disabled props is still OG
      This hook is more applicable in smaller scenarios :)

    • @1337-coder
      @1337-coder Рік тому

      you can just make the api call with try catch. handle the error case with the old array (closures) then directly call setToDos as i demonstrate below. no need for this hook. very simple:
      function onSubmit(e: FormEvent) {
      e.preventDefault();
      if (inputRef.current == null) return;
      async function apiCall() {
      try {
      const newToDo = await createToDo(inputref.current.value);
      setToDos(prev => [...prev, newToDo]);
      } catch {
      setToDos([...prev])
      }
      }
      apiCall();
      setToDos(prev => [...prev, {id: crypto.randomUUID(), title: inputref.current.value}]);
      }

    • @HorstKirkPageKian
      @HorstKirkPageKian Рік тому +1

      absolutely agreed

  • @llamasaylol
    @llamasaylol Рік тому +7

    Question: What happens if you add 2 items to the list in quick succession (i.e. before the "server" has responded to the first addition)? When the server responds to the first addition, will the pending second addition vanish from the list? If so, then the array example is silly and it would be better to use a hook that has logic that understands what to do (which you'd think they could do if they were a bit more clever about the use of the reducer and pulling in other bits of information into the hook's constructor).

    • @pbdivyesh
      @pbdivyesh Рік тому

      That is a valid use-case. Though I feel since we are not removing any items from the list the previous-version of the list would be containing that item-1 and just appending item-2 as well. I completely understand the point you are trying to make, and I also have the apprehension with this method, as we are just writing more lines of code for the functionality.

    • @QwDragon
      @QwDragon Рік тому

      @@pbdivyesh but when the server replies to one of the requests, second pending item will disappear.

    • @pbdivyesh
      @pbdivyesh Рік тому

      @@QwDragon that is what is this optimistic update does it won't drop the already item but only store-update the one based on the response.
      I'm sure, internally they would be using an identifier ID that is attached and once it's promise is resolved they only update the value for that item and not others. Think of it like a reference to caller to a new instance of a function.
      Hence that's why it is still experimental.
      Client side would maintain that id for that item, maybe a bit different in next.js server side components but pretty much the same idea

  • @grimmdanny
    @grimmdanny Рік тому +1

    It seems like simply adding the new data to the list on submission-and gray it out if it doesn't have an actual ID from the server-and then update the data when it does come back from the server, would be simpler and cleaner than doing all that. I can't see how useOptimistic adds any usefulness.

  • @oidualx
    @oidualx Рік тому +10

    The question now is: when will React 18.3 come out so that we can actually use the new hooks? Version 18.2 came out over a year ago

  • @MarekLichtner7
    @MarekLichtner7 Рік тому +1

    you can use also swr library for that with even cleaner API

  • @ubaidkhan426
    @ubaidkhan426 Рік тому +1

    I don't understand the idea of useOptimistic hook, we could even use the todos setter to update the list before making the request and call the setter again after the request fulfill.

  • @stuartallen2001
    @stuartallen2001 Рік тому

    A lot of the questions people are commenting are answered in the full video. I highly recommend watching

  • @Kayotesden
    @Kayotesden Рік тому +2

    I dont quite understand...
    Isnt useOptimistic just another useState holding the 'todos' temporarily. We can easily achieve the same useOptimistic logic using useState, actually, the lines of code would be the same as well, as onSubmit is first updating the temp state, then the 'real' todos state...

    • @PipsUniversity577
      @PipsUniversity577 4 місяці тому

      Exactly my question, I really don’t see the use case of useOptimistic

  • @VKD007
    @VKD007 Рік тому +1

    Oh man this was needed long back. I hope with next iteration of react we get this.

  • @adtc
    @adtc Рік тому +1

    This is real cool! I hope it becomes released soon, because it will be quite useful.

  • @TheStickofWar
    @TheStickofWar Рік тому +4

    Just to be clear for those of you who develop software in React, this is not something you will want to use all the time.
    A user for something important should not ever be unintentionally tricked into believing they made some change via an action of theirs if it hasn’t been validated. Meaning if someone needed to publish some calculation results for example, then this is something you shouldn’t use at all - it would be awful if your user hit publish and got false feedback from the application, then closed the tab immediately.
    Use this responsibly, use it when your user is unlikely to move away from the page so the rectifying can occur on failed API calls, and don’t use it for anything that can have consequences for your user. Like saving settings, updating passwords, sending important data etc

  • @mambans
    @mambans Рік тому +2

    How does it handle errors from the request? If a request fails I would like to remove my optimisticTodo. I can't quite seem to see the big pros with this, it just saves me from writing like 1 row of code for replacing the old value. How does it know which value to replace?

  • @vaibhav5711
    @vaibhav5711 Рік тому

    Love your tutorials ❤. Just yesterday I watched tRPC, Zod, Prisma tutorials from your channel. Please make a complete tutorial on Turborepo too 🙏. Best regards.

  • @archis3
    @archis3 Рік тому

    This is incredible! Thanks Kyle

  • @0xtz_
    @0xtz_ Рік тому +1

    I saw this in swr hmm any video soon ?

  • @alexavery8182
    @alexavery8182 Рік тому +2

    Hullo hullo
    I was wondering if you could do an Axios crash course video. There's a lot of features in the library that many (myself included) aren't fully aware of and your crash course vids always deliver concepts so succinctly

  • @roguesherlock
    @roguesherlock Рік тому +2

    does it like diff the values when the setTodos is set after the server response or does it just replaces everything entirely? In the former case we'd have to pass something for it to be able to diff right, in the later case did they just make a reactive state hook haha?

  • @taihatranduc8613
    @taihatranduc8613 8 місяців тому

    Thank you. Love you

  • @emmanuelameyaw7
    @emmanuelameyaw7 Рік тому

    Just a request sir, can you please make a complete Typescript + React video, I think that would really help out. Thank you

  • @poriaasrzad4042
    @poriaasrzad4042 Рік тому

    very useful ,
    thanks kyle

  • @petarkolev6928
    @petarkolev6928 Рік тому +1

    I can't find this method exported in my React project and I am using React 18.2.0. Do I need to add some kind of flags in a config somewhere?

  • @jametime7491
    @jametime7491 Рік тому +2

    Ok, I like the new videos, but the problem with covering all these new features is that I don't get to use them now, secondly, by the time they are released I may not even remember that this is a possibility and just do something on my own.

    • @dixztube
      @dixztube Рік тому

      Watch later when you need it

  • @LuKaSSthEBosS
    @LuKaSSthEBosS Рік тому +1

    Will that task be done today? Use optimistic

  • @dominiquehamet1776
    @dominiquehamet1776 11 місяців тому

    Wowww ! Thx a lot.

  • @NOTHING-en2ue
    @NOTHING-en2ue Рік тому

    very great tutorial, thanks a lot ❤

  • @anastaleb3617
    @anastaleb3617 Рік тому

    Great explaining

  • @reaper84
    @reaper84 11 місяців тому

    That is indeed pretty cool

  • @sahilatahar
    @sahilatahar Рік тому

    I am upset with you , Mr. Kyle. Why you didn't add like or reaction button in your blog website because I love these blog this is what I want and I want to show my happiness. Thank u for this amazing blogs.

  • @stancobridge
    @stancobridge Рік тому

    Thanks

  • @orlinchirinos1981
    @orlinchirinos1981 Рік тому +4

    You can connect php language with react?

  • @doyin_dimeji
    @doyin_dimeji Рік тому +1

    How does this compare to the mutate function for useSWR hook?

  • @hosinhatami7271
    @hosinhatami7271 Місяць тому

    دمت گرم خیلی دید کانلی از این مونو ریپو و کارکردش گرفتم

  • @rajeshsathish1817
    @rajeshsathish1817 Рік тому

    Will it re-render the component twice in this case since we’re using additional state?

  • @prashantvatsa6685
    @prashantvatsa6685 Рік тому

    Can you please make a video on react grid layout

  • @DisturbedNeo
    @DisturbedNeo Рік тому

    Pretty sure this is meant to be used for Next server actions, not a React SPA.

  • @ihatelov1n
    @ihatelov1n Рік тому

    Did they implemented usePessimistic hook?

  • @aymanechaaba
    @aymanechaaba Рік тому

    I'm getting 2 results at the same time, the server value doesn't override the optimistic value

  • @kirarevcrow
    @kirarevcrow Рік тому +2

    What if the server request fails? Isn't it confusing for the user?

    • @LarsKniep
      @LarsKniep Рік тому

      You can show some notification and the entry will dissapear

    • @MrBluemoon74
      @MrBluemoon74 Рік тому

      i also would like to know how you 'reset' the optomisicTodos back to the todos list, because the todos variable does not change? do i do setTodos(prev => prev) or do i need to make a clone of the array?

  • @mateja176
    @mateja176 Рік тому +1

    What about rollbacks?

  • @jakee2455
    @jakee2455 Рік тому

    What about if a user assumes a task is complete and navigates away from the page while the server is still rendering with an error?
    Edit: I don't have time to watch the full video at the moment as well as read the comments

  • @alexartigas9181
    @alexartigas9181 Рік тому

    Or you can just set the state before awaiting the response. That's the whole point of optimistic updates, it's just a strategy agnostic to React, React hooks, or any other framework 😅

  • @VietLe-hw8fy
    @VietLe-hw8fy Рік тому

    Can optimistic hook prevent UI from being blocked when rendering a huge content?

  • @HolySl0w
    @HolySl0w Рік тому

    that's kinda amazing

  • @matthewbarberdev
    @matthewbarberdev Рік тому

    So it's kinda like database transactions?

  • @sandrosxila
    @sandrosxila 8 місяців тому

    Will it fallback to the previous state if the request fails?

  • @אלעדר
    @אלעדר 6 місяців тому

    What happens if the server fails adding the TODO ?

  • @ZacharyFleischman
    @ZacharyFleischman Рік тому

    What if the user clicks twice really fast? How does the optimistic update know which entry in the list to overwrite? Does it just wipe the entire optimistic update state and replace it the second the first set state is called?

  • @azeek
    @azeek Рік тому

    Dude this is so cool 🎉🎉🎉

  • @Ghuboss
    @Ghuboss 2 місяці тому

    what happens if you add multiple values to optimistic at once? the ui gets updates immediately with the new todos. but then the first item is registered in the server (lets say after a few seconds), would it wipe all your new todos from the optimistic?

  • @champechilufya1458
    @champechilufya1458 3 місяці тому

    What about handking errors ? Does it just remove optimistic update ?

  • @felipecouto9044
    @felipecouto9044 Рік тому

    Woow! Amaziing content!

  • @MaxFerney
    @MaxFerney Рік тому

    this almost feels like a react flavored rxjs behaviors and subjects

  • @pupfriend
    @pupfriend Рік тому

    Whats old is new. Meteor did this 8 years ago.

  • @Shubham-yc6nz
    @Shubham-yc6nz Рік тому

    Can we use it with normal nextjs api calls using axios?

  • @CheskerHard63
    @CheskerHard63 Рік тому

    hi kyle good video thank you for it

  • @GreenLikeGrass
    @GreenLikeGrass Рік тому

    wait... is wait a native JavaScript function?

  • @willembeltman
    @willembeltman Рік тому

    Isnt this extremely easy to do in javascript?

  • @АнтонСтрока
    @АнтонСтрока Рік тому +3

    but if api fails ?

    • @UnderCtrl
      @UnderCtrl Рік тому

      For this video's example, it'll remove the new todo that was added optimistically.

    • @micheledellaquila7671
      @micheledellaquila7671 Рік тому

      I believe you call setTodos(prev => prev) without adding anything so use optimistic will overwrite itself and the current list will be equal to the previous one

    • @АнтонСтрока
      @АнтонСтрока Рік тому

      @@micheledellaquila7671 so i see a new ítem in a list, and then if fails its removes from list? Not a best user expireince i think

    • @ДиалектикаКринжа
      @ДиалектикаКринжа Рік тому

      @@micheledellaquila7671 but what if there is 2 pending todos and only one returns an error?

  • @antonsvyatchenko8876
    @antonsvyatchenko8876 Рік тому

    Missing example with an error from the server

  • @tipsyterry
    @tipsyterry Рік тому

    Hey. So what happens when the server returns an error response - how does the UI revert to the previous state?

  • @johncerpa3782
    @johncerpa3782 Рік тому

    great video

  • @oskarszwajkowski
    @oskarszwajkowski Рік тому

    Where is docs for this hook? I cannot see it in description and google does not help that much.

    • @WebDevSimplified
      @WebDevSimplified  Рік тому

      There are no docs yet. I had to look through the source code and commit messages.

  • @LucasNovaes2023
    @LucasNovaes2023 Рік тому +1

    I know a lot of things we see in web development are actually "tricks", but this is just straight up lying to the user at this point. When I add an item on a list on a web platform, and I see the new item on that list, I trust that the item has actually been added. So, even if I leave the page immediately, when I come back, I trust the added item would be there as the application suggested. If it's not, that's totally unexpected.

    • @bowiemtl
      @bowiemtl Рік тому

      Things like loading spinners have always been indicative of an unfinished interaction, this case had opacity as an example but the same concept applies

  • @harjitkainth8525
    @harjitkainth8525 Рік тому

    Where can I find this in the react docs?

  • @Slaci-vl2io
    @Slaci-vl2io 5 місяців тому

    If I weren't so poor, I would be Kyle's patreon.

  • @aamiramin6112
    @aamiramin6112 Рік тому

    Awesome

  • @xtraszone
    @xtraszone Рік тому

    How many times have you told optimistic in this video ?

  • @koksikskkj7937
    @koksikskkj7937 Рік тому +1

    Well thats cool, but cannot we just add another state for "pending" something and conditionaly render? Just render normall items and on the end the pending one and change state fot both on this same time. Doesnt look hard

    • @MrLucasEss
      @MrLucasEss Рік тому

      If you want to conditionally render your optimistic todos, you don’t need optimistic updates, as this is mainly a UX thing.

  • @Nova-900
    @Nova-900 Рік тому +1

    how many times he said to do's in one minute 💀💀💀💀💀💀

  • @mfpears
    @mfpears Рік тому

    Optimistic updates are deceptive updates

  • @ariassingh462
    @ariassingh462 Рік тому +4

    Enjoyed until you got to the reducer part, then I got redux PTSD

  • @gunasekarant6498
    @gunasekarant6498 Рік тому +1

    We could have used useState itself? What is the difference please explain?

    • @MrBluemoon74
      @MrBluemoon74 Рік тому

      if you useState, than by the time the api call returns you have to update two states, todos and optomisticTodos.

  • @theg4gatekeeper477
    @theg4gatekeeper477 9 місяців тому

    fech tnayek azebi ?

  • @tanvirshaikh3511
    @tanvirshaikh3511 Рік тому

    please create svelte tutorial

  • @yadusolparterre
    @yadusolparterre Рік тому

    Not a big fan of storing derived state. This creates more complexity than it solves

  • @MilanDrazic
    @MilanDrazic Рік тому

    I'm sick of fetching data waiting promises in React 😢

  • @jggabayno
    @jggabayno Рік тому

    hello everyone

  • @AndiAbrudan
    @AndiAbrudan Рік тому +2

    I hate optimistic updates with a passion, and I wouldn't wish them on my worst enemy.
    They should change the name to "Silent fails" instead, to make it more accurate.
    This is a feature I would never implement in any application I build.

  • @magnusred2945
    @magnusred2945 Рік тому

    Bro why u look like Gigachad

  • @jacksonbourne
    @jacksonbourne Рік тому +1

    another day another React hook to fix their terrible initial approach

  • @valen8560
    @valen8560 Рік тому +1

    if you think you're proficient enough in react, just skip to 4:40

  • @greendsnow
    @greendsnow Рік тому +2

    React and fast, two words that do not go well together

  • @moritz_p
    @moritz_p Рік тому

    I don't get why this would be part of the library. I could've written that hook myself in 5-10 minutes. It should be part of some utility library that provides some smart hooks but not of React itself

  • @Gohealt
    @Gohealt Рік тому +3

    The fact of the matter is, most of youtubers/influencers are cashing in on every new gimmick that React throws out, and making a video out of it BUT in reality, it is a big headache for all React devs who are working in the REAL WORLD(not working with todo lists at work to say the least) and has to deal with breaking changes of React on regular basis. In this regard, React sucks.

  • @mtranchi
    @mtranchi Рік тому +4

    I'm reckoning your views are in React, or you've chosen to focus on that, or whatever... i wish you'd do some more plain.js frameworks, or at least throw them in once in a while. You make great vids, but i've got no interest in React. Regardless, keep making outstanding vids!

    • @ra2enjoyer708
      @ra2enjoyer708 Рік тому

      The real challenge of writing in "plain.js" is not to accidentally shit out a badly documented badly written pseudo-framework along the way.

  • @dixztube
    @dixztube Рік тому

    I’m so over react lol long live htmlx

  • @arunkaiser
    @arunkaiser Рік тому

    First comment

  • @MahmoudAbdullahAnani
    @MahmoudAbdullahAnani Рік тому

    You have more than a million followers, why don't you dub or even translate your videos!!

  • @-mahmoudadel2628
    @-mahmoudadel2628 Рік тому

    I watched some videos for you 3 years ago, and now I see this .. why did you become speak fast ? 🥺

  • @mlnima
    @mlnima Рік тому

    you need break, your tics getting worse bro, take some rest

  • @blablablablablablblablabla
    @blablablablablablblablabla Рік тому

    This is just another tutorial I cant use at work because we wont switch to experimental react... Please it is annoying to see such good tutorials for nothing

  • @Seedzification
    @Seedzification Рік тому

    PLEASE stop shaking your head when you speak