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.
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
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
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
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?
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!
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 TH-cam comment section). Those not suitable cases (like youtube comment sections) causes infamous problem of "the TH-camr deleted my comment" and tons of unnecessary conficts between content creator and audience.
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
@@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 :)
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}]); }
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).
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 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
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...
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.
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?
Love your tutorials ❤. Just yesterday I watched tRPC, Zod, Prisma tutorials from your channel. Please make a complete tutorial on Turborepo too 🙏. Best regards.
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?
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.
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?
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?
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.
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
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
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.
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
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 😅
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
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.
Things like loading spinners have always been indicative of an unfinished interaction, this case had opacity as an example but the same concept applies
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
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.
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!
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
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.
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
A brand new video from kyle. A brand new todo application
I wish someone would make something else for once. Anything else.
💀💀💀💀💀😭😭😭😭😭
Just what I’ve always wanted.
@@snivelslike what? a counter? 😂
he just wants to explain the hook with the simplest way possible.
I’m loving how you’re covering upcoming react features. Thank you!
Love this man! Soft voice with clean explanation
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.
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
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
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
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
So good! Cant wait for it to become available in stable react version.
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?
This is incredible! Thanks Kyle
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!
Absolutely amazing, the react team (vercel / next) is implementing all the features from Remix lol …
From react-query :)
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 🙌
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?
Oh man this was needed long back. I hope with next iteration of react we get this.
very great tutorial, thanks a lot ❤
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 TH-cam comment section). Those not suitable cases (like youtube comment sections) causes infamous problem of "the TH-camr deleted my comment" and tons of unnecessary conficts between content creator and audience.
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
@@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 :)
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}]);
}
absolutely agreed
This is real cool! I hope it becomes released soon, because it will be quite useful.
you can use also swr library for that with even cleaner API
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).
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.
@@pbdivyesh but when the server replies to one of the requests, second pending item will disappear.
@@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
A lot of the questions people are commenting are answered in the full video. I highly recommend watching
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...
Exactly my question, I really don’t see the use case of useOptimistic
very useful ,
thanks kyle
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.
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?
You can connect php language with react?
Yes
Love your tutorials ❤. Just yesterday I watched tRPC, Zod, Prisma tutorials from your channel. Please make a complete tutorial on Turborepo too 🙏. Best regards.
Hey. So what happens when the server returns an error response - how does the UI revert to the previous state?
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?
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
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.
Thank you. Love you
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?
What if the server request fails? Isn't it confusing for the user?
You can show some notification and the entry will dissapear
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?
Wowww ! Thx a lot.
How does this compare to the mutate function for useSWR hook?
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.
Will it re-render the component twice in this case since we’re using additional state?
Dude this is so cool 🎉🎉🎉
Where can I find this in the react docs?
Great explaining
That is indeed pretty cool
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
What about handking errors ? Does it just remove optimistic update ?
Will it fallback to the previous state if the request fails?
Just a request sir, can you please make a complete Typescript + React video, I think that would really help out. Thank you
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
Can we use it with normal nextjs api calls using axios?
I saw this in swr hmm any video soon ?
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.
Watch later when you need it
دمت گرم خیلی دید کانلی از این مونو ریپو و کارکردش گرفتم
What happens if the server fails adding the TODO ?
Where is docs for this hook? I cannot see it in description and google does not help that much.
There are no docs yet. I had to look through the source code and commit messages.
hi kyle good video thank you for it
I'm getting 2 results at the same time, the server value doesn't override the optimistic value
Can optimistic hook prevent UI from being blocked when rendering a huge content?
Can you please make a video on react grid layout
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
Woow! Amaziing content!
Will that task be done today? Use optimistic
Did they implemented usePessimistic hook?
Thanks
this almost feels like a react flavored rxjs behaviors and subjects
Pretty sure this is meant to be used for Next server actions, not a React SPA.
Whats old is new. Meteor did this 8 years ago.
Isnt this extremely easy to do in javascript?
that's kinda amazing
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 😅
So it's kinda like database transactions?
Missing example with an error from the server
but if api fails ?
For this video's example, it'll remove the new todo that was added optimistically.
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?
We could have used useState itself? What is the difference please explain?
if you useState, than by the time the api call returns you have to update two states, todos and optomisticTodos.
What about rollbacks?
great video
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.
Things like loading spinners have always been indicative of an unfinished interaction, this case had opacity as an example but the same concept applies
wait... is wait a native JavaScript function?
how many times he said to do's in one minute 💀💀💀💀💀💀
If I weren't so poor, I would be Kyle's patreon.
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
If you want to conditionally render your optimistic todos, you don’t need optimistic updates, as this is mainly a UX thing.
Enjoyed until you got to the reducer part, then I got redux PTSD
How many times have you told optimistic in this video ?
Optimistic updates are deceptive updates
please create svelte tutorial
fech tnayek azebi ?
Awesome
Not a big fan of storing derived state. This creates more complexity than it solves
I'm sick of fetching data waiting promises in React 😢
hello everyone
if you think you're proficient enough in react, just skip to 4:40
Bro why u look like Gigachad
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.
React and fast, two words that do not go well together
As opposed to what?
another day another React hook to fix their terrible initial approach
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!
The real challenge of writing in "plain.js" is not to accidentally shit out a badly documented badly written pseudo-framework along the way.
You have more than a million followers, why don't you dub or even translate your videos!!
I’m so over react lol long live htmlx
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
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.
First comment
I watched some videos for you 3 years ago, and now I see this .. why did you become speak fast ? 🥺
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
you need break, your tics getting worse bro, take some rest
PLEASE stop shaking your head when you speak