I Cannot Believe React Made A Hook For This

React Simplified Course: reactsimplified.com/?...
React recently announced a new experimental hook that makes working with optimistic updates so much easier. This saves so much boilerplate code and gives your users a much better experience.
📚 Materials/References:
React Simplified Course: reactsimplified.com/?...
🌎 Find Me Here:
My Blog: blog.webdevsimplified.com
My Courses: courses.webdevsimplified.com
Patreon: / webdevsimplified
Twitter: / devsimplified
Discord: / discord
GitHub: github.com/WebDevSimplified
CodePen: codepen.io/WebDevSimplified
⏱️ Timestamps:
00:00 - Introduction
00:34 - What are optimistic updates
01:13 - Why optimistic updates are hard
02:05 - useOptimistic hook basics
06:38 - useOptimistic hook advanced
#ReactJS #WDS #useOptimistic

Пікірлер: 146

  • @MoinKhan_10
    @MoinKhan_1011 ай бұрын

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

  • @snivels

    @snivels

    11 ай бұрын

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

  • @steinkuste3492

    @steinkuste3492

    11 ай бұрын

    💀💀💀💀💀😭😭😭😭😭

  • @NicholasShanks

    @NicholasShanks

    11 ай бұрын

    Just what I’ve always wanted.

  • @ricko13

    @ricko13

    11 ай бұрын

    ​@@snivelslike what? a counter? 😂

  • @big-jo89

    @big-jo89

    11 ай бұрын

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

  • @EvertJunior
    @EvertJunior11 ай бұрын

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

  • @SurajSingh-fg6eq
    @SurajSingh-fg6eq11 ай бұрын

    Love this man! Soft voice with clean explanation

  • @gasparsigma
    @gasparsigma11 ай бұрын

    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

  • @AzaroPk
    @AzaroPk11 ай бұрын

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

  • @vaibhav5711
    @vaibhav571111 ай бұрын

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

  • @creaky2436
    @creaky243611 ай бұрын

    Can’t you just set the state immediately then set state again once the data comes in? Or something like that?

  • @brandonz404

    @brandonz404

    11 ай бұрын

    This is a great question.. he mentioned in the beginning that it handles errored responses.. but never went into more detail. I'd love to know the advantages of doing this over your solution, since now I'm wondering the same thing

  • @PipsUniversity577

    @PipsUniversity577

    Ай бұрын

    Exactly my question

  • @MikheilDzuliashvili

    @MikheilDzuliashvili

    3 күн бұрын

    i have same question xD, why we need this extra stuff i never used it actually and even its experimental, i mean thats should not be that hard to implement

  • @NOTHING-en2ue
    @NOTHING-en2ue11 ай бұрын

    very great tutorial, thanks a lot ❤

  • @archis3
    @archis311 ай бұрын

    This is incredible! Thanks Kyle

  • @MarekLichtner7
    @MarekLichtner711 ай бұрын

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

  • @adtc
    @adtc11 ай бұрын

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

  • @roguesherlock
    @roguesherlock11 ай бұрын

    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?

  • @leodevbro
    @leodevbro11 ай бұрын

    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

    11 ай бұрын

    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

    11 ай бұрын

    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

    8 ай бұрын

    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

  • @VKD007
    @VKD00711 ай бұрын

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

  • @dave6012
    @dave601211 ай бұрын

    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!

  • @doyin_dimeji
    @doyin_dimeji11 ай бұрын

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

  • @poriaasrzad4042
    @poriaasrzad404211 ай бұрын

    very useful , thanks kyle

  • @mambans
    @mambans11 ай бұрын

    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?

  • @emmanuelameyaw5686
    @emmanuelameyaw568611 ай бұрын

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

  • @petarkolev6928
    @petarkolev692811 ай бұрын

    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?

  • @rajeshsathish1817
    @rajeshsathish181711 ай бұрын

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

  • @bogdanfilimon2486
    @bogdanfilimon248611 ай бұрын

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

  • @gasparsigma

    @gasparsigma

    11 ай бұрын

    From react-query :)

  • @kinxori

    @kinxori

    11 ай бұрын

    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 🙌

  • @taihatranduc8613
    @taihatranduc86136 ай бұрын

    Thank you. Love you

  • @ZacharyFleischman
    @ZacharyFleischman10 ай бұрын

    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?

  • @anastaleb3617
    @anastaleb361711 ай бұрын

    Great explaining

  • @grimmdanny
    @grimmdanny11 ай бұрын

    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.

  • @doc8527
    @doc852711 ай бұрын

    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 KZread comment section). Those not suitable cases (like youtube comment sections) causes infamous problem of "the KZreadr deleted my comment" and tons of unnecessary conficts between content creator and audience.

  • @alexradu1921

    @alexradu1921

    11 ай бұрын

    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

    11 ай бұрын

    @@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

    11 ай бұрын

    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

    10 ай бұрын

    absolutely agreed

  • @tipsyterry
    @tipsyterry11 ай бұрын

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

  • @dominiquehamet1776
    @dominiquehamet17769 ай бұрын

    Wowww ! Thx a lot.

  • @oidualx
    @oidualx11 ай бұрын

    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

  • @alexavery8182
    @alexavery818211 ай бұрын

    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

  • @VietLe-hw8fy
    @VietLe-hw8fy11 ай бұрын

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

  • @CheskerHard63
    @CheskerHard6311 ай бұрын

    hi kyle good video thank you for it

  • @Shubham-yc6nz
    @Shubham-yc6nz10 ай бұрын

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

  • @azeek
    @azeek11 ай бұрын

    Dude this is so cool 🎉🎉🎉

  • @ubaidkhan426
    @ubaidkhan42611 ай бұрын

    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.

  • @llamasaylol
    @llamasaylol11 ай бұрын

    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

    11 ай бұрын

    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

    11 ай бұрын

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

  • @pbdivyesh

    @pbdivyesh

    11 ай бұрын

    @@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

  • @LuKaSSthEBosS
    @LuKaSSthEBosS11 ай бұрын

    Will that task be done today? Use optimistic

  • @harjitkainth8525
    @harjitkainth852511 ай бұрын

    Where can I find this in the react docs?

  • @Kayotesden
    @Kayotesden11 ай бұрын

    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

    Ай бұрын

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

  • @champechilufya1458
    @champechilufya145821 күн бұрын

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

  • @sandrosxila
    @sandrosxila5 ай бұрын

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

  • @orlinchirinos1981
    @orlinchirinos198111 ай бұрын

    You can connect php language with react?

  • @adarsh-chakraborty

    @adarsh-chakraborty

    11 ай бұрын

    Yes

  • @user-ck6yl6qb2g
    @user-ck6yl6qb2g4 ай бұрын

    What happens if the server fails adding the TODO ?

  • @jametime7491
    @jametime749111 ай бұрын

    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

    11 ай бұрын

    Watch later when you need it

  • @Ghuboss
    @Ghuboss27 минут бұрын

    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?

  • @mateja176
    @mateja17611 ай бұрын

    What about rollbacks?

  • @0xtz_
    @0xtz_10 ай бұрын

    I saw this in swr hmm any video soon ?

  • @stuartallen2001
    @stuartallen200110 ай бұрын

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

  • @prashantvatsa6685
    @prashantvatsa668511 ай бұрын

    Can you please make a video on react grid layout

  • @jakee2455
    @jakee245511 ай бұрын

    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

  • @Maglaque1
    @Maglaque111 ай бұрын

    Did they implemented usePessimistic hook?

  • @MaxFerney
    @MaxFerney11 ай бұрын

    this almost feels like a react flavored rxjs behaviors and subjects

  • @oskarszwajkowski
    @oskarszwajkowski11 ай бұрын

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

  • @WebDevSimplified

    @WebDevSimplified

    11 ай бұрын

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

  • @reaper84
    @reaper848 ай бұрын

    That is indeed pretty cool

  • @felipecouto9044
    @felipecouto904411 ай бұрын

    Woow! Amaziing content!

  • @antonsvyatchenko8876
    @antonsvyatchenko887611 ай бұрын

    Missing example with an error from the server

  • @stancobridge
    @stancobridge11 ай бұрын

    Thanks

  • @misterkilluminati6949
    @misterkilluminati694911 ай бұрын

    Can this hook be used in production ?

  • @kirarevcrow
    @kirarevcrow11 ай бұрын

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

  • @LarsKniep

    @LarsKniep

    11 ай бұрын

    You can show some notification and the entry will dissapear

  • @MrBluemoon74

    @MrBluemoon74

    11 ай бұрын

    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?

  • @sahilatahar
    @sahilatahar11 ай бұрын

    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.

  • @matthewbarberdev
    @matthewbarberdev11 ай бұрын

    So it's kinda like database transactions?

  • @willembeltman
    @willembeltman10 ай бұрын

    Isnt this extremely easy to do in javascript?

  • @aymanechaaba
    @aymanechaaba10 ай бұрын

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

  • @HolySl0w
    @HolySl0w11 ай бұрын

    that's kinda amazing

  • @DisturbedNeo
    @DisturbedNeo10 ай бұрын

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

  • @alexartigas9181
    @alexartigas918111 ай бұрын

    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 😅

  • @johncerpa3782
    @johncerpa378211 ай бұрын

    great video

  • @GreenLikeGrass
    @GreenLikeGrass11 ай бұрын

    wait... is wait a native JavaScript function?

  • @koksikskkj7937
    @koksikskkj793711 ай бұрын

    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

    11 ай бұрын

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

  • @user-gq3zw5ob3v
    @user-gq3zw5ob3v11 ай бұрын

    but if api fails ?

  • @UnderCtrl

    @UnderCtrl

    11 ай бұрын

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

  • @micheledellaquila7671

    @micheledellaquila7671

    11 ай бұрын

    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

  • @user-gq3zw5ob3v

    @user-gq3zw5ob3v

    11 ай бұрын

    @@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

  • @user-oj4pt3fj2m

    @user-oj4pt3fj2m

    11 ай бұрын

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

  • @tanvirshaikh3511
    @tanvirshaikh351111 ай бұрын

    please create svelte tutorial

  • @aamiramin6112
    @aamiramin611211 ай бұрын

    Awesome

  • @pupfriend
    @pupfriend11 ай бұрын

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

  • @theg4gatekeeper477
    @theg4gatekeeper4776 ай бұрын

    fech tnayek azebi ?

  • @xtraszone
    @xtraszone11 ай бұрын

    How many times have you told optimistic in this video ?

  • @Slaci-vl2io
    @Slaci-vl2io2 ай бұрын

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

  • @Nova-900
    @Nova-90011 ай бұрын

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

  • @gunasekarant6498
    @gunasekarant649811 ай бұрын

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

  • @MrBluemoon74

    @MrBluemoon74

    11 ай бұрын

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

  • @mfpears
    @mfpears11 ай бұрын

    Optimistic updates are deceptive updates

  • @LucasNovaes2023
    @LucasNovaes202311 ай бұрын

    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

    11 ай бұрын

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

  • @jggabayno
    @jggabayno11 ай бұрын

    hello everyone

  • @TheStickofWar
    @TheStickofWar11 ай бұрын

    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

  • @MilanDrazic
    @MilanDrazic11 ай бұрын

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

  • @AndiAbrudan
    @AndiAbrudan11 ай бұрын

    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.

  • @yadusolparterre
    @yadusolparterre11 ай бұрын

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

  • @ariassingh462
    @ariassingh46211 ай бұрын

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

  • @magnusred2945
    @magnusred294511 ай бұрын

    Bro why u look like Gigachad

  • @RegalWK
    @RegalWK11 ай бұрын

    Better to use dedicated libs for this ¯\_(ツ)_/¯ Like state management, or some client to your apis like Apollo graphql/ react query etc.

  • @moritz_p
    @moritz_p11 ай бұрын

    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

  • @greendsnow
    @greendsnow11 ай бұрын

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

  • @ra2enjoyer708

    @ra2enjoyer708

    11 ай бұрын

    As opposed to what?

  • @dixztube
    @dixztube11 ай бұрын

    I’m so over react lol long live htmlx

  • @arunkaiser
    @arunkaiser11 ай бұрын

    First comment

  • @valen8560
    @valen856011 ай бұрын

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

  • @MahmoudAbdullahAnani
    @MahmoudAbdullahAnani11 ай бұрын

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

  • @mtranchi
    @mtranchi11 ай бұрын

    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

    11 ай бұрын

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

  • @-mahmoudadel2628
    @-mahmoudadel262810 ай бұрын

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

  • @jacksonbourne
    @jacksonbourne10 ай бұрын

    another day another React hook to fix their terrible initial approach

  • @user-ir3yw8bs4i
    @user-ir3yw8bs4i11 ай бұрын

    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.

  • @Seedzification
    @Seedzification11 ай бұрын

    PLEASE stop shaking your head when you speak