I Cannot Believe React Made A Hook For This

  Рет қаралды 103,888

Web Dev Simplified

Web Dev Simplified

Күн бұрын

Пікірлер: 149
@MoinKhan_10
@MoinKhan_10 Жыл бұрын
A brand new video from kyle. A brand new todo application
@snivels
@snivels Жыл бұрын
I wish someone would make something else for once. Anything else.
@steinkuste3492
@steinkuste3492 Жыл бұрын
💀💀💀💀💀😭😭😭😭😭
@NicholasShanks
@NicholasShanks Жыл бұрын
Just what I’ve always wanted.
@ricko13
@ricko13 Жыл бұрын
​@@snivelslike what? a counter? 😂
@big-jo89
@big-jo89 Жыл бұрын
he just wants to explain the hook with the simplest way possible.
@EvertJunior
@EvertJunior Жыл бұрын
I’m loving how you’re covering upcoming react features. Thank you!
@SurajSingh-fg6eq
@SurajSingh-fg6eq Жыл бұрын
Love this man! Soft voice with clean explanation
@gasparsigma
@gasparsigma Жыл бұрын
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
@creaky2436
@creaky2436 Жыл бұрын
Can’t you just set the state immediately then set state again once the data comes in? Or something like that?
@brandonz404
@brandonz404 Жыл бұрын
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 3 ай бұрын
Exactly my question
@MikheilDzuliashvili
@MikheilDzuliashvili 2 ай бұрын
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
@creaky2436
@creaky2436 Ай бұрын
@@MikheilDzuliashvili Yeah i really don't understand useOptimistic still lol. 11 months later and still haven't touched it and likely never will. I use a simplistic approach - state/suspense boundaries/coupled with next loading.tsx file etc. Literally all you need. A ui indicator- a spinner, skeleton, subtle blur animation, etc while the user waits a few ms until data has been updated.
@bogdanfilimon2486
@bogdanfilimon2486 Жыл бұрын
Absolutely amazing, the react team (vercel / next) is implementing all the features from Remix lol …
@gasparsigma
@gasparsigma Жыл бұрын
From react-query :)
@kinxori
@kinxori Жыл бұрын
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 🙌
@leodevbro
@leodevbro Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
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 10 ай бұрын
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
@AzaroPk
@AzaroPk Жыл бұрын
So good! Cant wait for it to become available in stable react version.
@doc8527
@doc8527 Жыл бұрын
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 KZbin comment section). Those not suitable cases (like youtube comment sections) causes infamous problem of "the KZbinr deleted my comment" and tons of unnecessary conficts between content creator and audience.
@alexradu1921
@alexradu1921 Жыл бұрын
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 Жыл бұрын
absolutely agreed
@hosinhatami7271
@hosinhatami7271 Ай бұрын
دمت گرم خیلی دید کانلی از این مونو ریپو و کارکردش گرفتم
@dave6012
@dave6012 Жыл бұрын
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!
@Kayotesden
@Kayotesden Жыл бұрын
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 3 ай бұрын
Exactly my question, I really don’t see the use case of useOptimistic
@MarekLichtner7
@MarekLichtner7 Жыл бұрын
you can use also swr library for that with even cleaner API
@VKD007
@VKD007 Жыл бұрын
Oh man this was needed long back. I hope with next iteration of react we get this.
@aymanechaaba
@aymanechaaba Жыл бұрын
I'm getting 2 results at the same time, the server value doesn't override the optimistic value
@oidualx
@oidualx Жыл бұрын
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
@adtc
@adtc Жыл бұрын
This is real cool! I hope it becomes released soon, because it will be quite useful.
@archis3
@archis3 Жыл бұрын
This is incredible! Thanks Kyle
@ubaidkhan426
@ubaidkhan426 Жыл бұрын
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.
@taihatranduc8613
@taihatranduc8613 8 ай бұрын
Thank you. Love you
@llamasaylol
@llamasaylol Жыл бұрын
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
@reaper84
@reaper84 10 ай бұрын
That is indeed pretty cool
@dominiquehamet1776
@dominiquehamet1776 11 ай бұрын
Wowww ! Thx a lot.
@NOTHING-en2ue
@NOTHING-en2ue Жыл бұрын
very great tutorial, thanks a lot ❤
@TheStickofWar
@TheStickofWar Жыл бұрын
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
@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.
@petarkolev6928
@petarkolev6928 Жыл бұрын
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?
@poriaasrzad4042
@poriaasrzad4042 Жыл бұрын
very useful , thanks kyle
@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.
@stuartallen2001
@stuartallen2001 Жыл бұрын
A lot of the questions people are commenting are answered in the full video. I highly recommend watching
@mateja176
@mateja176 Жыл бұрын
What about rollbacks?
@emmanuelameyaw5686
@emmanuelameyaw5686 Жыл бұрын
Just a request sir, can you please make a complete Typescript + React video, I think that would really help out. Thank you
@roguesherlock
@roguesherlock Жыл бұрын
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?
@orlinchirinos1981
@orlinchirinos1981 Жыл бұрын
You can connect php language with react?
@adarsh-chakraborty
@adarsh-chakraborty Жыл бұрын
Yes
@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?
@DisturbedNeo
@DisturbedNeo Жыл бұрын
Pretty sure this is meant to be used for Next server actions, not a React SPA.
@אלעדר
@אלעדר 6 ай бұрын
What happens if the server fails adding the TODO ?
@alexavery8182
@alexavery8182 Жыл бұрын
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
@jametime7491
@jametime7491 Жыл бұрын
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
@champechilufya1458
@champechilufya1458 2 ай бұрын
What about handking errors ? Does it just remove optimistic update ?
@0xtz_
@0xtz_ Жыл бұрын
I saw this in swr hmm any video soon ?
@doyin_dimeji
@doyin_dimeji Жыл бұрын
How does this compare to the mutate function for useSWR hook?
@LuKaSSthEBosS
@LuKaSSthEBosS Жыл бұрын
Will that task be done today? Use optimistic
@pupfriend
@pupfriend Жыл бұрын
Whats old is new. Meteor did this 8 years ago.
@anastaleb3617
@anastaleb3617 Жыл бұрын
Great explaining
@tipsyterry
@tipsyterry Жыл бұрын
Hey. So what happens when the server returns an error response - how does the UI revert to the previous state?
@sandrosxila
@sandrosxila 7 ай бұрын
Will it fallback to the previous state if the request fails?
@kirarevcrow
@kirarevcrow Жыл бұрын
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?
@HolySl0w
@HolySl0w Жыл бұрын
that's kinda amazing
@matthewbarberdev
@matthewbarberdev Жыл бұрын
So it's kinda like database transactions?
@MaxFerney
@MaxFerney Жыл бұрын
this almost feels like a react flavored rxjs behaviors and subjects
@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?
@rajeshsathish1817
@rajeshsathish1817 Жыл бұрын
Will it re-render the component twice in this case since we’re using additional state?
@stancobridge
@stancobridge Жыл бұрын
Thanks
@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
@VietLe-hw8fy
@VietLe-hw8fy Жыл бұрын
Can optimistic hook prevent UI from being blocked when rendering a huge content?
@CheskerHard63
@CheskerHard63 Жыл бұрын
hi kyle good video thank you for it
@azeek
@azeek Жыл бұрын
Dude this is so cool 🎉🎉🎉
@antonsvyatchenko8876
@antonsvyatchenko8876 Жыл бұрын
Missing example with an error from the server
@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 😅
@Shubham-yc6nz
@Shubham-yc6nz Жыл бұрын
Can we use it with normal nextjs api calls using axios?
@willembeltman
@willembeltman Жыл бұрын
Isnt this extremely easy to do in javascript?
@GreenLikeGrass
@GreenLikeGrass Жыл бұрын
wait... is wait a native JavaScript function?
@felipecouto9044
@felipecouto9044 Жыл бұрын
Woow! Amaziing content!
@Slaci-vl2io
@Slaci-vl2io 4 ай бұрын
If I weren't so poor, I would be Kyle's patreon.
@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.
@harjitkainth8525
@harjitkainth8525 Жыл бұрын
Where can I find this in the react docs?
@Nova-900
@Nova-900 Жыл бұрын
how many times he said to do's in one minute 💀💀💀💀💀💀
@johncerpa3782
@johncerpa3782 Жыл бұрын
great video
@theg4gatekeeper477
@theg4gatekeeper477 8 ай бұрын
fech tnayek azebi ?
@ariassingh462
@ariassingh462 Жыл бұрын
Enjoyed until you got to the reducer part, then I got redux PTSD
@LucasNovaes2023
@LucasNovaes2023 Жыл бұрын
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
@АнтонСтрока
@АнтонСтрока Жыл бұрын
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?
@gunasekarant6498
@gunasekarant6498 Жыл бұрын
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.
@tanvirshaikh3511
@tanvirshaikh3511 Жыл бұрын
please create svelte tutorial
@yadusolparterre
@yadusolparterre Жыл бұрын
Not a big fan of storing derived state. This creates more complexity than it solves
@xtraszone
@xtraszone Жыл бұрын
How many times have you told optimistic in this video ?
@MilanDrazic
@MilanDrazic Жыл бұрын
I'm sick of fetching data waiting promises in React 😢
@koksikskkj7937
@koksikskkj7937 Жыл бұрын
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.
@aamiramin6112
@aamiramin6112 Жыл бұрын
Awesome
@mfpears
@mfpears Жыл бұрын
Optimistic updates are deceptive updates
@AndiAbrudan
@AndiAbrudan Жыл бұрын
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.
@jggabayno
@jggabayno Жыл бұрын
hello everyone
@magnusred2945
@magnusred2945 Жыл бұрын
Bro why u look like Gigachad
@greendsnow
@greendsnow Жыл бұрын
React and fast, two words that do not go well together
@ra2enjoyer708
@ra2enjoyer708 Жыл бұрын
As opposed to what?
@MahmoudAbdullahAnani
@MahmoudAbdullahAnani Жыл бұрын
You have more than a million followers, why don't you dub or even translate your videos!!
@dixztube
@dixztube Жыл бұрын
I’m so over react lol long live htmlx
@jacksonbourne
@jacksonbourne Жыл бұрын
another day another React hook to fix their terrible initial approach
@valen8560
@valen8560 Жыл бұрын
if you think you're proficient enough in react, just skip to 4:40
@-mahmoudadel2628
@-mahmoudadel2628 Жыл бұрын
I watched some videos for you 3 years ago, and now I see this .. why did you become speak fast ? 🥺
@mtranchi
@mtranchi Жыл бұрын
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.
@mlnima
@mlnima Жыл бұрын
you need break, your tics getting worse bro, take some rest
@Gohealt
@Gohealt Жыл бұрын
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.
@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
@arunkaiser
@arunkaiser Жыл бұрын
First comment
@Seedzification
@Seedzification Жыл бұрын
PLEASE stop shaking your head when you speak
@misterkilluminati6949
@misterkilluminati6949 Жыл бұрын
Can this hook be used in production ?
@Pareshbpatel
@Pareshbpatel Жыл бұрын
{}2023-09-03}
@RegalWK
@RegalWK Жыл бұрын
Better to use dedicated libs for this ¯\_(ツ)_/¯ Like state management, or some client to your apis like Apollo graphql/ react query etc.
@mambans
@mambans Жыл бұрын
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?
Learn useRef in 11 Minutes
10:20
Web Dev Simplified
Рет қаралды 639 М.
React Query Is (Still) Essential - My Favorite React Library
11:04
Theo - t3․gg
Рет қаралды 152 М.
Пришёл к другу на ночёвку 😂
01:00
Cadrol&Fatich
Рет қаралды 11 МЛН
Поветкин заставил себя уважать!
01:00
МИНУС БАЛЛ
Рет қаралды 6 МЛН
This is the Only Right Way to Write React clean-code - SOLID
18:23
Speed Up Your React Apps With Code Splitting
16:50
Web Dev Simplified
Рет қаралды 383 М.
Why Signals Are Better Than React Hooks
16:30
Web Dev Simplified
Рет қаралды 477 М.
18 Weird and Wonderful ways I use Docker
26:18
NetworkChuck
Рет қаралды 150 М.
The Story of React Query
8:55
uidotdev
Рет қаралды 106 М.
Node.js Doesn’t Suck Anymore
16:59
Web Dev Simplified
Рет қаралды 111 М.
Top 6 React Hook Mistakes Beginners Make
21:18
Web Dev Simplified
Рет қаралды 573 М.
They made React great again?
4:11
Fireship
Рет қаралды 1 МЛН