Learn useRef in 11 Minutes

  Рет қаралды 649,419

Web Dev Simplified

Web Dev Simplified

Күн бұрын

🚨 IMPORTANT:
Full React Course: courses.webdev...
In this video I cover everything you need to know about the useRef hook. I go over all the main use cases for useRef as well as many common mistakes that developers make. This is part of a series of React videos where I cover all the important hooks in React.
📚 Materials/References:
useRef Blog Article: blog.webdevsim...
React Hooks Playlist: • React Hooks
🧠 Concepts Covered:
How to use hooks in React
How to store values between renders in React function components
How to use the useRef hook
🌎 Find Me Here:
My Blog: blog.webdevsim...
My Courses: courses.webdev...
Patreon: / webdevsimplified
Twitter: / devsimplified
Discord: / discord
GitHub: github.com/Web...
CodePen: codepen.io/Web...
#ReactJs #WDS #useRef

Пікірлер: 626
@dhruvmaindola5767
@dhruvmaindola5767 Жыл бұрын
If anyone is still confused about the last example. Here is a simple explanation. Just keep three things in mind. 1. useState() causes re-render. 2. useRef() DOESN'T cause re-render. 3. useEffect() runs AFTER render. So the flow goes like this. name = "" prevName = "" -> Lets say you put "A" in the text field , so setName() runs. Changes the value of name = "A" to this. Component renders. -> Then useEffect is run where you set prevName to name. prevName is the same as name which is "A" but here comes the 2nd point i wrote. useRef() DOESN'T cause re-render. -> So when you changed the name , component got rendered and useEffect caused the prevName to change. But the thing is that component has already been rendered with whatever value prevName HAD before setName() got called. prevName is not STORING the previous value of name. It is only DISPLAYING the previous value of name. Hope this helps.
@omyerawar7976
@omyerawar7976 Жыл бұрын
Great Explanation 🤩
@user-zv6bv7eu8k
@user-zv6bv7eu8k Жыл бұрын
Is it safe to say that useEffect() uses the data from the previous render ??? and I understand we store it in a useRef() since it wont cause a rerender .... but what's the difference using a useRef() variable oppose to just updating a normal variable ... NEED HELP
@waynerandom11
@waynerandom11 Жыл бұрын
@@user-zv6bv7eu8k Because if you change the declaration to be const prevName = , then prevName would be set to at the start of every re-render whereas const prevName = useRef() will set prevName to only on the first render. Subsequent renders will set prevName to the whatever the last assigned value was. Hope that helps!
@sarveshwarpandey9516
@sarveshwarpandey9516 Жыл бұрын
thanks!
@dongbinkim3773
@dongbinkim3773 10 ай бұрын
@@waynerandom11 Thanks for your great explanation!
@Gabrielito300
@Gabrielito300 4 жыл бұрын
I rarely use to comment on videos, but i think this video deserves an specific acknowledgment. It was an excellent explanation about useRef, and the way that you showed the difference between it and states is super important. I hope you keep helping us, amateur web developers, to keep improving. Hope you have a lovely weekend ❤
@WebDevSimplified
@WebDevSimplified 4 жыл бұрын
Thank you so much!
@mattmarkus4868
@mattmarkus4868 2 жыл бұрын
i agree. i would like to see more advanced stuff, because he explains things very well and clearly.
@wawayltd
@wawayltd 3 жыл бұрын
I hope this comment will help someone who can't get a grip on it like I couldn't for some time... When you are trying to understand logic of these processes explained in the video, just keep in mind one important thing - useEffect() only runs AFTER your component is rendered. Like in the last example where we trying to get previous value of our name, I would say that prevValue.current is not actually storing the value of our previous name, it displays it as component renders - then useEffect runs, prevValue.current now storing value of current name, but because useRef doesn't make component to re-render, it "keeps that in mind", but doesn't display it till the next time component is rendered. Oh gosh.. I was hoping I'll put it simple. I hope it makes sense. It took me while to figure out logic and I feel need to share it with people.
@avineshgupta6264
@avineshgupta6264 3 жыл бұрын
Thanx dude
@bikerguy3338
@bikerguy3338 2 жыл бұрын
I was struggling to understand this too. Thanks for clarifying what's happening!
@balluvwdwadi8995
@balluvwdwadi8995 Жыл бұрын
Thank you!🎉
@AbhishekBhandari-om9hu
@AbhishekBhandari-om9hu Жыл бұрын
thanks
@daniillitvinenko4348
@daniillitvinenko4348 Жыл бұрын
Thank you, I was specifically looking for this in the comments
@elie3423
@elie3423 3 жыл бұрын
for people confused of what is happening in the last use case of useref, useEffect by definition runs after the things gets rendered. so he is basically printing the value of the useState before assigning it in the useEffect
@anandkrishnanmj95
@anandkrishnanmj95 3 жыл бұрын
Thanks for clearing that, have been looking through the comments to figure that out.😃
@anandkrishnanmj95
@anandkrishnanmj95 3 жыл бұрын
And after the render, useEffect gets called and changes the value of prevName.current to current name, And even though the prevName.current currently holds the current name after useEffect, it won't trigger a re-render And that's why the prevName.current used in the return statement prints the previousName right?
@veselinmladenov7941
@veselinmladenov7941 2 жыл бұрын
Thank you for that Elie, I spent a decent time trying to understand what is going on and why is behaving that way.
@zksumon847
@zksumon847 2 жыл бұрын
Thanks a lot
@marco8673
@marco8673 Жыл бұрын
thank you very much!!!
@cristianouzumaki2455
@cristianouzumaki2455 4 жыл бұрын
I might purchase your course despite already knowing react. great vids bro.
@WebDevSimplified
@WebDevSimplified 4 жыл бұрын
Thank you!
@shyambhujel8797
@shyambhujel8797 3 жыл бұрын
@@WebDevSimplified c b0
@shyambhujel8797
@shyambhujel8797 3 жыл бұрын
@@WebDevSimplifiedy yyyyyyyy
@shyambhujel8797
@shyambhujel8797 3 жыл бұрын
@@WebDevSimplified hhyyt5
@siddheshb.kukade4685
@siddheshb.kukade4685 3 жыл бұрын
Lol
@mrarc197
@mrarc197 4 жыл бұрын
Im using most of things you teach on daily basis but I am still watching your videos and in many cases Im finding gems that I never even thought about. Good job mate, keep doing it, its good content.
@nazarabdurakhimov2859
@nazarabdurakhimov2859 Жыл бұрын
Hey Kyle, I'm watching some paid React course, but when something is unclear, I open KZbin and specifically look for your videos - I find them super useful, you can explain difficult concepts in a clear and relaxed way. I can see how every aspect of your videos (intro, speech, explanation, examples) are thoroughly thought out. Thx a lot for all of your effort!
@sakshichoudhary7842
@sakshichoudhary7842 3 жыл бұрын
Finally understood Refs properly.. You are a saviour❤️
@callixtegirard4782
@callixtegirard4782 2 ай бұрын
Man you're just so much the best React teacher out there. Perfectly structured, bite-sized lessons. 💪
@alizarean5080
@alizarean5080 8 ай бұрын
after searching for about 5 hours this video finally answered all my questions. I can't thank you enough buddy. I wish you the best of bests.
@jayantakumarroy543
@jayantakumarroy543 3 жыл бұрын
I really like the calm voice without super hyped energy,coz that's what i need for an educational video
@gerasmaster2099
@gerasmaster2099 2 жыл бұрын
Every time I need to learn something new about JavaScript, I look for your videos. You explain everything so clear it couldn't be better
@temzeks
@temzeks 3 жыл бұрын
not gonna lie, i went through the useRef from one of the react books today, and i didnt understand what it was, this video somewhat made it brighter for me, but not entirely. Gotta rewatch it in the morning! Keep it up
@cobaltninjas
@cobaltninjas 2 жыл бұрын
I honestly never thought of using useRef for anything other than DOM elements. This is brilliant.
@iamnadeemzafar
@iamnadeemzafar 3 жыл бұрын
I was googling for the actual use case of useRef and after long time i got satisfied watching your video ... You told exactly what i wanted to know.... A lot of tutorial had the same caption but not worth satisfying. And the most appreciable is that you only took few minutes..
@luis_soul1
@luis_soul1 3 жыл бұрын
I struggled a little bit trying to understand Ref in React and I constantly found a bunch of explanations with examples but no other like this video. It made me understand everything. Thank you so much Kyle, shout out to you for explaining Ref very simple and concise.
@zain2314
@zain2314 4 жыл бұрын
bro i have been following your tutorial and none of them have failed to amaze me, your explaination is so onpoint and simple.
@liamwelsh5565
@liamwelsh5565 2 жыл бұрын
Little shortcut. Instead of doing const something = useRef(), you can use object destructoring and set it to const {current: something} = useRef(). This allows you to access your ref without needing .current.
@hatem.tommy.lamine
@hatem.tommy.lamine Жыл бұрын
doesn't work, because you have to set ref={something} later on
@mtsurov
@mtsurov Жыл бұрын
Best 10 minutes I've spent today.
@DaggieBlanqx
@DaggieBlanqx 4 жыл бұрын
After watching the video I accidentally closed the tab. Now I am back, just give this video a like because your tutorials are really helpful.
@aldhie33
@aldhie33 2 жыл бұрын
thank you so much. i spend two hours read the doc and it still confuse me, but with your explanation, it makes me understand the way to use this hooks. 😲😲
@fahmidatasnimlisa2592
@fahmidatasnimlisa2592 3 жыл бұрын
I'm pulling an all-nighter and i got my final exam on React in a couple of hours. Thanks for the video, so greatly explained
@siddharthmagadum16
@siddharthmagadum16 3 жыл бұрын
Just for my reference 9:07 . Q) Why is prevName not same as name, as due to state change the render has happened and after the render has happened, the useEffect has called, hence prevName should be same as name (updated)? Ans - > the state is set asynchronously. > the callback function in useEffect is executed synchronously. I believe this happens - As the state is set asynchronously, the rendering happens first and then the state value changes. Within that time, as rendering has alredy been done, the useEffect is executed and the old value of name is declared to prevName. Till now, the asynchronous state is completed and the name is got the new value.
@tinujos8306
@tinujos8306 2 жыл бұрын
But why use useRef when you can store the previous name value in a simple let variable?
@siddharthmagadum16
@siddharthmagadum16 2 жыл бұрын
@@tinujos8306 Those variable values will be reset after every re-render, and you will lose the value stored
@praveenbabu9048
@praveenbabu9048 3 ай бұрын
I don't think it happens this way. Instead I believe it works like this -Initially both state and ref are '' -User types 'a' -State change (synchronous) state = 'a' , ref = '' -Re-render as state is changed -All the UI is painted with the current state and ref value. -Use effect is called since the component is mounted after re-rendering -Current state value is assigned to the ref. (now ref = 'a') -UI remains same (as change in ref doesn't cause any re-render) -User types 'b' next to 'a' -State change (synchronous) state = 'ab' , ref = 'a' -Re-render as state is changed -All the UI is painted with the current state('ab') and ref value('a'). Correct me If I am wrong.
@raghavsingh5592
@raghavsingh5592 3 жыл бұрын
You solved the problem for which I sat for hours. Thank you very much.
@andrewsmichael7047
@andrewsmichael7047 2 жыл бұрын
Thank you so much bro, I used to be confused about refs most times even the react docs didn't make it as clear as this video. Thanks a lot
@limji-siang6496
@limji-siang6496 3 жыл бұрын
For the first example of not causing infinite loops we can add the name dependencies in the useEffect too.
@seshaganesh8323
@seshaganesh8323 2 жыл бұрын
No,.. it will have a bug. Initially it will re-render once as it have changed the counter variable which is a state which over mutation cause a re-render. So an empty input have a count of 1 but we need a count of 0. This is where ref are used which dont cause re-rendering
@joeellul-turner1280
@joeellul-turner1280 2 жыл бұрын
That's what I thought
@tejasmuthya4492
@tejasmuthya4492 2 жыл бұрын
GOD BLESS YOU! I have a React interview tomorrow and feel very confident after watching your useMemo, useCallback and useRef videos!
@wcw23085
@wcw23085 3 жыл бұрын
YOU ARE A LIFESAVER!!!! Been searching for how to reference a DOM node in React and here you are showing me what I've been looking for the WHOLE DAMN DAY. THNAK YOU!!!!!!!! AHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH
@mountainscott5274
@mountainscott5274 3 жыл бұрын
this is a good explanation but it is important to understand that the same can be achieved at 2:40 by coding: useEffect(()=>{ setCount(prevCount=> prevCount + 1) }, [name]) the second parameter to the useEffect hook tells the function to only update when the state changes for the variable in square brackets. In the case, the variable is "name" and so the count would only update for every keystroke in the input box (which has a value based on the state of "name").
@vasilkotsev9923
@vasilkotsev9923 3 жыл бұрын
I've noticed the same fact and started to read the comments if anybody had noticed it too. So the first use case is not so useful. We can achieve the same result with adding [name] in the second parameter.
@GoonCity777
@GoonCity777 10 ай бұрын
Honestly this is better than college. I would even say this is better than a bootcamp too.
@usmanfarooq2334
@usmanfarooq2334 3 ай бұрын
for the people that are confused by the last example, let me try to explain what's happening: you need to remember 3 RULES : 1. useState() --> causes re-render 2. UseEffect() --> runs AFTER render (aka DOM is already rendered and all possible variables/components have already been "shown/printed" in the browser) 3. useRef --> does NOT cause re-render (but the change_in_value/mutation of the Ref object persists across renders) now as a dry run: the moment setState("abc") is called, React Instantly renders the DOM which causes the value inside "prevName.current" to get printed on the browser aswell ....then, AFTER rendering, React notices that it needs to run the useEffect also {since the variable="name" was passed inside the useEffect's "depndecy array", and that variable's value has changed because of the setState("abc") called } .... when React runs the UseEffect() it basically changes the value stored inside "prevName.current" and sets it to be "abc", BUT since the DOM was rendered already (remember RULE no.2 that I mentioned above), the latest value stored inside "prevName.current" won't get to be shown on the browser, since even though useEffect has mutated/changed prevName's value, It did it tooooo late (outdated value of prevName.current has already been printed in the browser .. and the outdated value was accessible in This instance of the render because of the "persistent nature" of UseRef objects .... which is in accordance with RULE no.3), and we now wait for setState() to be called once again so that this value of "prevName.current" gets to be a part of the render (aka get printed in the browser).... but alas, in doing so, we will once again mutate/change the value inside "prevName.current' but it would be done "tooo late" (aka after we have already rendered/printed the outdated value inside "prevName.current")..... and this would go on and on and on
@evergreen7781
@evergreen7781 3 жыл бұрын
I think you have the best videos for react hooks on KZbin
@KamilHussainShaikh
@KamilHussainShaikh 3 жыл бұрын
The quality of your presentation is appreciated. Thank you for the videos. May Allah reward you for your efforts.
@starwarsfan9575
@starwarsfan9575 4 жыл бұрын
I don't get time to learn by myself because of busy work schedule but through your quick and easy videos like this one I am able to....thanks! Keep up the good work!
@sudarshankj
@sudarshankj 3 жыл бұрын
What I truly love about your videos are: They are really crisp and cover the crux of the topic magically in a very small amount of time! That takes great skill, keep it up!
@balajiganesh4246
@balajiganesh4246 3 жыл бұрын
That was super useful bro. I always felt this concept was too complex and always avoided it. Now, I have a decent clartity within 10 mins. Thanks a lot
@abrahamgeorge7466
@abrahamgeorge7466 7 ай бұрын
Very high quality content.After watching many useRef videos ,i only understood from your video.
@anilsuyal
@anilsuyal 6 ай бұрын
Wow! what a straightforwad amazing explanation to useRef. I was tired understanding it from lot of videos and docuementation, but understood only because of you. thank you sir
@dmytro-skh
@dmytro-skh 2 жыл бұрын
it is really surprising how good you are at explanations
@exceptionalbuildingservices
@exceptionalbuildingservices 4 жыл бұрын
Mate I watched so many videos and read so many articles, but I never saw anything like yours! Short and very well explained. That's what I needed! Thanks!!!
@deepanshukhorwal8938
@deepanshukhorwal8938 Жыл бұрын
your content is fabulous and most useful for working professionals
@fluntimes
@fluntimes 2 жыл бұрын
The. Best. Explanation. Of. useRef. On. The. Internet!
@viniciusalvess
@viniciusalvess 2 жыл бұрын
I had a situation where I had to read qr codes, but the qr code component triggered and event multiple times when the camera was reading the qr code because of motion and low delay tim. I couldn't increase the delay time, because it would take too long to scan many qr codes and useRef hook helped me to solve my issue. Thanks Kyle for the great video.
@saranshmehra8577
@saranshmehra8577 2 жыл бұрын
I somehow stumbled upon this video... Amazing Content.!! just wow!!. If you wanna learn refs then this is the ultimate source.
@nigelbess5168
@nigelbess5168 7 ай бұрын
Your content really breaks these down in a useful way. Thanks so much, youve saved me a lot of time.
@Kreshel1
@Kreshel1 3 жыл бұрын
Great video Kyle. What would be the difference in a functional component of using ref and just declaring a variable outside the function? something like this: let counter = 0 function functionalComponentToBeRendered(){ //hooks, state etc return {counter} }
@prince5922
@prince5922 2 жыл бұрын
That value will be same for every component, not unique to every component we create.
@andreranulfo-dev8607
@andreranulfo-dev8607 2 жыл бұрын
So happy to see this Channel almost reaching 1MI subscribers.
@IvinAustan
@IvinAustan Жыл бұрын
Really had a great experience of knowing all the react hooks use cases. You did a very good job. Kudos, man!!!
@LearnTubeOriginal
@LearnTubeOriginal 2 жыл бұрын
All this while I felt that useRef is useful for DOM manipulations only, but this video is an eyeopener
@fatemehzareie5423
@fatemehzareie5423 Жыл бұрын
I finally understand "useRef" thank u 😍😍✌️✌️
@DonWhatever221
@DonWhatever221 2 жыл бұрын
2:40 Giving the useEffect a dependency array with "name" in it will lead to the desired output without unnecessary rerenders. So this specific example is indeed possible with useState...
@basitobaid6903
@basitobaid6903 Жыл бұрын
Kyle seriously knows what he is talking about !!!!!!!!!!!!!!!!!
@charleschen3538
@charleschen3538 4 ай бұрын
The last example works because useEffect runs AFTER render. So, a better way would be to update the useRef value during the onChange handler like: onChange={(e) => { prevName.current = name; setName(e.target.value) } in this case the useRef value actually stores the previous name and render it out. (Found this out though a StackOverflow post)
@nareshbhati7527
@nareshbhati7527 3 жыл бұрын
Thank you, you always give new knowledge. In 10 minutes you clear the concepts of 1 hour. Thank you so much for saving us a lot of time.
@damilareabiola3709
@damilareabiola3709 2 жыл бұрын
I don't know it was impossible two years ago but using useState and useEffect worked without creating an infinite loop by specifying that I only want the hook to run when name changes (which I learnt from your "UseEffect video" :) ).
@quietcalm7299
@quietcalm7299 4 жыл бұрын
I never comment on videos but this explanation was so spot on - it helped me so much converting a tutorial that was using dom selectors into react-syntax. So thanks a lot :)))
@musthafapa
@musthafapa 2 жыл бұрын
This video literally saved me from pushing the bad code into production server.
@b1ackbrd1
@b1ackbrd1 3 жыл бұрын
After watching this I used it in one of our Video player component and its just awesome. Thanks a lot for this video
@raffibags
@raffibags 4 жыл бұрын
By far the best explanation of the useRefs hook I've seen. Well done.
@hdjfgt
@hdjfgt 3 жыл бұрын
Wow I think useRef finally clicked for me thanks to this video! Thanks a lot!
@chunkwanchan5503
@chunkwanchan5503 2 жыл бұрын
thank you! think this hook really shed light on my mini project. I can save the previous dom state and render it back on the page now
@natnaelsisay1424
@natnaelsisay1424 3 жыл бұрын
No words, Just Thank you brother
@stellawatson2978
@stellawatson2978 3 жыл бұрын
@Web Dev Simplified It's amazing how you know the concepts at such depth. We learn from you. But where do you learn from? From where do you get such amazing knowledge over everything. Would love to know that too. 😜😃
@user-fg6ng7ej6w
@user-fg6ng7ej6w 2 жыл бұрын
this playlist is very helpful: clearly explained, yet complete and concise. thanks.
@karthickr1994
@karthickr1994 4 жыл бұрын
This guy deserves a like. Impressive mate. Thank you.
@hdsz7738
@hdsz7738 3 жыл бұрын
The best part of your videos is the ASMR of your keyboard
@csmnitemare4532
@csmnitemare4532 2 жыл бұрын
These vids are gold!!! thank you for helping this aspiring dev understand things that some seem to just gloss over or explain horribly.
@mr.RAND5584
@mr.RAND5584 4 жыл бұрын
useState with datalist html kinda have slowness performance issue. I used the useRef with datalist html and its working fine. thanks for your awesome tutorial. God Bless.
@k.l7111
@k.l7111 Жыл бұрын
Clear comparison with useState and nice explanation of rendering lifecycle. Thank you!
@RezHimself
@RezHimself 2 жыл бұрын
this video is so useful , now i know how to use useRef and useState , thanks
@franco-cespi
@franco-cespi 4 жыл бұрын
As with useMemo I thank you for thining down the difficult concepts of React. Greate examples! I can't wait to see some more hooks simplified.
@Travelmoments452
@Travelmoments452 4 ай бұрын
You need to explain the useEffect hook into more details into this video, on how it correlates with other hooks and within the component. Grant it this video is about useRef hook but every specific code you don't explain (useEffect) would make the code harder to comprehend. I noticed you tend to do that in your videos. You have great videos but a lot of times when you teach coding you just glance over a specific code within a set of codes. Please explain each on what code does and how they relate from each other. I have seen other tutorials that do that and that is extremely helpful. Specificity is key when teaching code and a lot of veteran coders don't understanding that (diff from actually coding vs teaching coding).
@rayanfernandes2631
@rayanfernandes2631 3 жыл бұрын
Clear cut explanation ... Thanks kyle.. You are amazing person.
@jackmiller2518
@jackmiller2518 Жыл бұрын
Straight forward, Perfectly explained with no bs, thanks a lot!
@ambrozykleks626
@ambrozykleks626 2 жыл бұрын
Great stuff, sir. Never thought about Ref that way.
@Ichigo-kurusaki580
@Ichigo-kurusaki580 2 жыл бұрын
Dude you explain such topics so good with easy examples and simple usecase that before even going anywhere else to understand some concept i made it a habit to go through your videos first. Thanks for uploading
@Rodo1802
@Rodo1802 Жыл бұрын
I love you, Kyle! You’ve made my React Day with this video. 🙏🏼 thank you!
@motilimkayes1352
@motilimkayes1352 4 жыл бұрын
Wow, thanks man, I'm going to re-watch this playlist every week or so for some time.
@rishabhgupta2085
@rishabhgupta2085 3 жыл бұрын
Most Clear 🔍 explanation on the web 🕸
@amitborkar2892
@amitborkar2892 4 жыл бұрын
You really explained it in an easy way mate. Could you also make a video on React-router?
@santra528
@santra528 3 жыл бұрын
Thanks Kyle, Now I understood how to work with useRef
@atheerapeter5174
@atheerapeter5174 4 жыл бұрын
I was wondering about how to grab elements in react and this golden video popped up so thank you so much
@FL4M3M4K3R
@FL4M3M4K3R Жыл бұрын
perfect explanation, so i dont need any more videos about topic. Its high level, thank you Kyle ;)
@hekskey
@hekskey 3 жыл бұрын
Good explanation. Another potentially useful way to take advantage of useRef() that sort of extends what you showed at the end is in cases where you might want to both read and update a state value inside of a useEffect(). If you were to try to do that with the state value directly, you would need to add it as a dependency for the useEffect(), which means that every time the useEffect() updated the state value, that would trigger the useEffect() to run again, creating an infinite loop. You can get around this by creating a useRef() proxy for the state value and then using that to _read_ the value in the useEffect() without needing to add it as a dependency. For example, this would create an infinite loop: ----- const [stateValue, setStateValue] = useState(0); useEffect(() => { console.log(stateValue); setStateValue(prevStateValue => prevStateValue + 1); }, [stateValue, setStateValue]); ----- But this would not create an infinite loop: ----- const [stateValue, setStateValue] = useState(0); const stateValue_ref = useRef(stateValue); useEffect(() => { stateValue_ref.current = stateValue; }, [stateValue]); // stateValue_ref.current is kept up-to-date every time stateValue changes useEffect(() => { console.log(stateValue_ref.current); setStateValue(prevStateValue => prevStateValue + 1); }, [setStateValue]); // no need to include stateValue_ref.current as a dependency ----- This is a trivial and unrealistic example, but it might be useful to keep in mind. A more realistic scenario might be one where you have to compare stateValueA and stateValueB when stateValueA changes and then update stateValueB accordingly. In that case, you'd add stateValueA as a dependency so it triggers the useEffect() when it changes and you'd use the above method to create a useRef() proxy for stateValueB that you could use for comparison inside the useEffect() before calling setStateValueB() to update the actual value in the state. Anyway, hope that's helpful.
@tarekghosn3648
@tarekghosn3648 2 жыл бұрын
thanks i look forward to my project finishing and being able to say your videos were abig part of it
@0x0abb
@0x0abb 2 жыл бұрын
Web Dev Simplified is so awesome - I agree -one must show gratitude - great work!
@dribvul
@dribvul 4 жыл бұрын
Please use dark background for chrome also 🙃!!. Your tutorials are really great, easy to understand.
@teletoby94
@teletoby94 Жыл бұрын
Thank you for the concise and easy to understand explainer. Love this and appreciate your work.
@jameskobe1716
@jameskobe1716 3 жыл бұрын
I think this is what i needed for my looping slider. I didn't know how to manage the previous / current / next slide without a messy code xD
@soorya3562
@soorya3562 3 жыл бұрын
Best explanation for useRef. Keep the goo work brother !
@go_all_the_way
@go_all_the_way 2 жыл бұрын
this video just saved my weekend
@durgaprasaddas6494
@durgaprasaddas6494 2 жыл бұрын
Man!! this is the most informative and well explained.
@LongBoy.0
@LongBoy.0 4 жыл бұрын
Finally an amazing explainer on useRef. Thanks!
@sam12345393
@sam12345393 2 жыл бұрын
Awesome explanation dude, I hardly comment on tech tuts, you are just so eloquent and precise. Keep up the good work!
@beb316ratnesh2
@beb316ratnesh2 7 ай бұрын
Great explanation directly from Docs 💀
@mochemiguel1233
@mochemiguel1233 2 жыл бұрын
Best useRef's tuto ever
@amitsharma-vq1ed
@amitsharma-vq1ed 2 жыл бұрын
If the last example looks confusing then try to forget useEffect for a moment and focus only on the render function. Your state got updated and it re-renders the component with the latest state in which prevName.current is not updated. It gets updated after the useEffect hook is called which is called after the render function but that doesn't re-render the UI as it is a ref update, not a state update.
@osamapervezriar387
@osamapervezriar387 Жыл бұрын
As always liking the video before actually watching it because i know the explanation is going to be amazing anyway! thanks Bro!!
@hamzahahmad1670
@hamzahahmad1670 4 жыл бұрын
Thank you for the thorough explanation. I have a question that is slightly unrelated to this lesson. At the 08:49 mark, how were you able to access the previous state of the name variable? Shouldn't the name variable have been updated till then? I tried figuring this out myself, so I also put a console.log in there. However, the console log was showing the updated state variable, while prevName.current still contained the old state. This is a bit confusing, so I would appreciate it if anyone could help or point me towards a resource that could explain this. Thank you.
@naymello
@naymello 4 жыл бұрын
useEffect is called after the render, so it renders the previous name and only after it happens it gets the value of the current name
@siddharthmagadum16
@siddharthmagadum16 3 жыл бұрын
> the state is set asynchronously. > the callback function in useEffect is executed synchronously. I believe this happens - As the state is set asynchronously, the rendering happens first and then the state value changes. Within that time, as rendering has alredy been done, the useEffect is executed and the old value of name is declared to prevName. Till now, the asynchronous state is completed and the name is got the new value.
@avonflex5031
@avonflex5031 3 жыл бұрын
@@siddharthmagadum16 have you done a setstate , then a {state} below it..
@vickylance
@vickylance 2 жыл бұрын
@@siddharthmagadum16 If the state is set asynchronously, the rendering happens first and then the state value changes. Then how does when you print the state value it has the latest value?
@Vivek-tj5xh
@Vivek-tj5xh 2 жыл бұрын
execute the same code, and console log the value of prevName.current you'll figure it out yourself
@klhmia
@klhmia 3 жыл бұрын
Watching your Authentication video which references useRef, which uses useEffect, which will likely reference something else, lol. Down the rabbit hole I go 👍 Thanks for all these useful videos, Kyle!
Learn useContext In 13 Minutes
13:08
Web Dev Simplified
Рет қаралды 731 М.
Learn React Hooks: useCallback - Simply Explained!
17:15
Cosden Solutions
Рет қаралды 104 М.
When u fight over the armrest
00:41
Adam W
Рет қаралды 30 МЛН
СКОЛЬКО ПАЛЬЦЕВ ТУТ?
00:16
Masomka
Рет қаралды 3,2 МЛН
Happy birthday to you by Secret Vlog
00:12
Secret Vlog
Рет қаралды 6 МЛН
FOREVER BUNNY
00:14
Natan por Aí
Рет қаралды 22 МЛН
Why Signals Are Better Than React Hooks
16:30
Web Dev Simplified
Рет қаралды 488 М.
Learn useMemo In 10 Minutes
10:42
Web Dev Simplified
Рет қаралды 489 М.
Never Forget React forwardRef Again
9:33
Coding in Public
Рет қаралды 22 М.
03- React Hooks - useRef [ARABIC]
15:47
Nour Homsi
Рет қаралды 11 М.
What is useRef Hook in React in telugu - 51 - ReactJs in Telugu
14:57
Telugu Skillhub
Рет қаралды 38 М.
10 React Hooks Explained // Plus Build your own from Scratch
13:15
Fireship
Рет қаралды 1,4 МЛН
Learn React Hooks: useRef - Simply Explained!
12:42
Cosden Solutions
Рет қаралды 112 М.
Learn useCallback In 8 Minutes
7:50
Web Dev Simplified
Рет қаралды 475 М.
When u fight over the armrest
00:41
Adam W
Рет қаралды 30 МЛН