React Hooks Tutorial – 10 – useEffect with cleanup
- December 29, 2023
- Posted by: MainInstructor
- Category: React
Video Title: React Hooks Tutorial – 10 – useEffect with cleanup
Welcome back everyone in the last video we learned how to mimic component did mount with use effect in this video let’s learn how to make use of the component we’ll unmount functionality that is possible with the effect hook to get an idea of why we need something like component we’ll unmount let’s take
A look at an example for this example I am going to create a container component for this hook Mouse which we implemented in the last video in the container I will simply add a button that will toggle the components visibility let’s get started I’m going to create a new
File called mouse container dot j/s within the file I’m going to use the react snippet RFC II to create a functional component I’m going to import you state from react and create a display state variable the variable name is display the setter is set display and the initial value is true
Next in the JSX I am going to add a button to toggle this display variable between true and false button toggle display on click we call set display passing in not off display so we are toggling the display value now if this display variable is set to true we
Render the hook mask component display and hook mouse finally in Abdo chess i will only include the mouse container component if we now save all the files and take a look at the browser we should have a button and the mouse coordinates when I move the mouse around you can see the
Coordinates updating and the log statement is printed every time the mouse moves now I’m going to click on the toggle display button this will effectively unmount the component from the Dom now when I try to move the mouse around we can see a warning in the console below the warning we can see
That the statement mouse event is still being logged so even though the component has been removed the event listener which belongs to that component is still listening and executing and this is what the warning indicates as well can’t perform a react State update on an unmounted component it indicates a
Memory leak in your application or in simpler words react is telling us hey you have unmounted the component but when you move your mouse around you’re asking me to update the state variables for x and y-coordinates the only problem is that component has been unmounted when you unmount a component
Make sure you cancel all your subscriptions and listeners in other words clean up after your component by the way this Mouse event is being logged from hook Malchus from log Mouse position this log statement right here now how do we handle the cleanup code if you are familiar with class components
It was pretty straightforward we had the component will unmount lifecycle hook where we could simply add window dot remove event listener mouse move and the handler is log Mouse position but how do we mimic this lifecycle functionality in use effect well it turns out to be pretty simple
The function that is passed to use effect can return a function which will be executed when the component will unmount so whatever you return is basically your cleanup function so from this arrow function passed to use effect we return another cleanup function return a function let’s log a statement component unmounting code and
We remove the event listener mouse move and log mouse position let’s save the files and test this out I move the mouse around we see the log statements a toggle display and you can see the statement component and mounting code in the console this means our event
Listener is now removed if I move the mouse around again you can see that we don’t have the warning or the log statements from before so this is the fourth example the point to make note of here is that when you want to execute some component cleanup code you include
It in a function and return that function from the function passed to use effect the cleanup code can be canceling subscriptions timers or even removing event handlers as we have just seen so that is about using the effect hook with cleanup code thank you guys for watching
Don’t forget subscribe I’ll see you guys in the next video
-
Sale!
Wireless WIFI Repeater Extender Amplifier Booster 300Mbps
$29.99$14.99 Add to cartWireless WIFI Repeater Extender Amplifier Booster 300Mbps
Categories: Electronics, Wi-Fi Router, Wireless Wi-Fi Extender Tags: 300Mbps, 802.11N, Amplifier, Booster, Extender, mobile wi-fi booster, Remote, WIFI, Wireless, Wireless WIFI, Wireless WIFI Repeater, Wireless WIFI Repeater Extender, Wireless WIFI Repeater Extender Amplifier, Wireless WIFI Repeater Extender Amplifier Booster, Wireless WIFI Repeater Extender Amplifier Booster 300Mbps$29.99$14.99 -
Sale!
Full RGB Light Design Gaming Headset Headphones with Mic
$24.99$14.99 Add to cartFull RGB Light Design Gaming Headset Headphones with Mic
Categories: Electronics, Gaming, Gaming Headsets Tags: Design, Full, Full RGB Light Design Gaming Headset, Full RGB Light Design Gaming Headset Headphones, Full RGB Light Design Gaming Headset Headphones with Mic, Gamer, Gaming, Gaming Headset Headphones, gaming headset wireless, Headphone, Headphones, Headset, Light, Mic, Package, RGB$24.99$14.99 -
Sale!
Wireless BlueTooth Multi-Device Keyboard Mouse Combo
$39.99$19.99 Add to cartWireless BlueTooth Multi-Device Keyboard Mouse Combo
Categories: Electronics, Gaming, Gaming Keyboards, Keyboard Mouse Combos Tags: Combo, Keyboard, keyboard mouse combos, Mouse, MultiDevice, Set, WireKeyboard Mouse Combo, Wireless, Wireless BlueTooth Keyboard Mouse Combo, Wireless BlueTooth Keyboard Mouse Combos, Wireless BlueTooth Multi-Device Keyboard Mouse Combo, Wireless BlueTooth Multi-Device Keyboard Mouse Combos$39.99$19.99 -
Sale!
High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar
$199.99$139.99 Add to cartHigh Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar
Categories: Gaming, Gaming Chairs Tags: Adjustable, Chair, computer chairs, Desk, Executive, Gaming, Girl, Headrest, High, High Back Leather Executive Adjustable Swivel Gaming Chair, High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest, High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar, High Back Leather Executive Adjustable Swivel Gaming Chairs, Leather, Lumbar, Office, Racing, Swivel$199.99$139.99 -
Sale!
Professional LED Light Wired Gaming Headphones with Noise Cancelling Microphone
$29.99$19.99 Select optionsProfessional LED Light Wired Gaming Headphones with Noise Cancelling Microphone
SKU: N/A Categories: Electronics, Gaming, Gaming Headsets Tags: Cancelling, Gaming, Gaming Headphones with Noise Cancelling Microphone, gaming headset, Headphones, Headset, LED, Light, Mic, Microphone, Noise, Professional, Professional LED Light Wired Gaming Headphones, Professional LED Light Wired Gaming Headphones with Noise Cancelling Microphone, Wired, Wired Gaming Headphones, Wired Gaming Headphones with Noise Cancelling Microphone$29.99$19.99 -
Sale!
Gaming Desk with LED Lights USB Power Outlets and Charging Ports
$349.99$249.99 Select optionsGaming Desk with LED Lights USB Power Outlets and Charging Ports
SKU: N/A Categories: Computer Desk, Gaming, Gaming Desk Tags: and Charging Ports, Charging, Desk, Desks, Gaming, gaming desk with led lights, Gaming Desks with LED Lights, Home, LED, Lights, Monitor, Office, Outlets, Port, Power, Room, Stand, USB, USB Power Outlets, White, Workstation$349.99$249.99 -
Sale!
Wired Mixed Backlit Anti-Ghosting Gaming Keyboard
$99.99$79.99 Add to cartWired Mixed Backlit Anti-Ghosting Gaming Keyboard
Categories: Electronics, Gaming, Gaming Keyboards Tags: Antighosting, Backlit, Blue, brown, Gaming, Gaming Keyboard, gaming keyboards, gaming keyboards and mouse, Keyboard, Laptop, Switch, Wired, Wired Mixed Backlit Anti-Ghosting Gaming Keyboard, Wired Mixed Backlit Anti-Ghosting Gaming Keyboards, Wired Mixed Backlit Gaming Keyboard$99.99$79.99 -
Sale!
Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset
$119.99$59.99 Add to cartWireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset
Categories: Electronics, Gaming, Gaming Headsets Tags: 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset, ANC, Audio, Bluetooth, Cancellation, Ear, Earphone, gaming headset, Headphones, Headset, Hi-Res Over the Ear Headphones Headset, HiRes, Noise, Wireless, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Headphones, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headsets$119.99$59.99 -
Sale!
Wired Sports Gaming Headset Earbuds with Microphone
$19.99$9.99 Select optionsWired Sports Gaming Headset Earbuds with Microphone
SKU: N/A Categories: Gaming, Gaming Headsets Tags: Accessories, Earbud, Earphone, Earphones, Gaming, gaming headset with microphone, Headphones, Headset, IOS, Microphone, Sports, Wired, Wired Sports Gaming Headset Earbuds, Wired Sports Gaming Headset Earbuds with Microphone, Wired Sports Headset Earbuds$19.99$9.99 -
Sale!
150W Universal Multi USB Fast Charger 16 Port MAX Charging Station
$49.99$29.99 Add to cart150W Universal Multi USB Fast Charger 16 Port MAX Charging Station
Categories: Charging Stations, Electronics Tags: 150W, 150W Charging Station, 150W Universal Multi USB Charging Station, 150W Universal Multi USB Fast Charger 16 Port MAX Charging Station, 150W Universal Multi USB Fast Charger 16 Port MAX Charging Stations, 150W Universal Multi USB MAX Charging Station, 16 Port MAX Charging Station, 3.5A, Charger, Charging, Fast, laptop charging stations, Max, Multi, Port, Stand, Station, Universal, USB$49.99$29.99
why am not understanding nothings
is teaching is bad please reply/????
thanks for this
At 1:38, shouldn’t you have done setDisplay( prevDisplay => !prevDisplay) since you are updating the value based on the previous value? If not, can you explain why you don’t use that code snippet
One more example of clean up func would be when we make an api call in a component and the component unmout before completion of the api in that case also its useful
Done thanks
UseEffect can replace componentWillUnmount to do cleanup code like removing listeners. If you return a function from the useEffect callback, that function will be executed by react when the component will unmount
I am Java backend developer and able to understand every easily and comfortably very easy react and feeling like full stack developer after this complete lecture and thank you very much vishwas Ji
Amazing teacher!!!!
amazing explanation, very clear
The problem with a 3-year-old tutorial:
– no warning message
– component unmounts but EvenListener is still listening
But he's a good teacher, there's a lot of good info in the code … and it's free!
Very good explanation
Hi Vishwas, as of now React v18, the warning message is not appearing but the mousemove handler is still in effect even the component is unmounted. Do you know how can I replicate the error/warning? Btw the return unmount is working.
In current time, react handel it it's own.
When we remove a component all method of that component no longer available.
Hi all, my question is why useffect return function is not run instantly on page load.. How browser knows that it must be run only after component is removed? And also, if you set event listener to the component that captures window size and displays it on the screen and when you resize the window even after you clean up the useffect functuon, it stil captures the widow size if you display the component again, how is that? How it can capture the change if it was removed?
So a good indication that one must use the cleanup function is when you see memory leak errors in the console. How else can I find out that I need to cleanup in case an error isn''t appearing?
I was able to perform the same operation even without useEffect, so I am not really able to understand the importance of Effect hook
Bro this cleanup function is not working now, I think React is updated now…
Khatarnak …you nailed it
this warning is not coming for me after clicking on toggle button. Can anyone pls help me understand why?
Does return statement/cleanup code get executed only on componentWillUnmount on all use cases of the dependency array? Or in other words, will return statement/cleanup code only get executed on componentWillUnmount if dependency array is missing or dependency array has dependencies?
thanks a ton for this fantastic tutorial. more power to you bruh!!! 💖💖
good video, mate. ty
Really great work here
if the return function is written but if it is empty, what will be the output ? does that make any change in output ?
Before 3 years this guy just helped me to learn angular and now react this guy is a pure blessing 🥰
Your toggle state use is incorrect. You should be passing a method into setDisplay. EG setDisplay(prev => !prev);
Simple and easy explanation, thank you.
Finally i get the purpose of return in useEffect, than you so much
Even though the component was un-mounted, how did the listener have access to the logMousePosition() function? Do unmounted components still remain in memory?
The great tutorial that I have ever seen on hooks as well as useeffect..Thanks for your excellency
not working with props and state
Great job man, thanks for this wonderful explanation 👍👍🙏🙏