React Hooks Tutorial – 27 – useMemo Hook
![*](https://i0.wp.com/allprowebdesigns.com/wp-content/uploads/2023/12/1704051941_maxresdefault.jpg?resize=840%2C430&ssl=1)
Video Title: React Hooks Tutorial – 27 – useMemo Hook
In the last video we had a look at the used call back hook which is used for performance optimization as it turns out there is another hook which is also concerned with performance optimization and that is the use memo hook in this video let’s understand with an example
How to make use of the memory hook I’m going to start off by creating a new file called counter dot GS within the file I’m going to use the snippet RFC II to create a functional component within the component I’m going to create two state variables using the
State hook so import you state and then within the component we create to counter variables counter one set counter one initial value of zero and the second counter to set counter to initial value of zero next I’m going to create two functions to increment the count value increment
One which is equal to an arrow function where we call set counter one passing in counter one plus one similarly Const increment to which is again an arrow function we call set counter to passing in counter to +1 finally in the JSX need to add two buttons to display the respective count
Values along with a click handler to increment the count values so div tag button count 1 which is counter 1 on click we increment 1 similarly the second button the tag button count 2 on click increment – all right let’s include the component in emojis
And head to the browser you can see that we have two counters I click on the first button and it’s count value increments click on the second button the second count value increments noting that we have not learned already well now we have a new requirement next to
The first counter we need to indicate whether the count value is an odd number or an even number sounds simple again so let’s go back to vs code and create a function that contains the logic Const is even which is an arrow function and within the body we return counter 1
Modulus 2 is equal to 0 next in the JSX we include a span tag and then we check is even we display even else we display odd all right let’s save this and test it out initially you can see that counter 1 is 0 which is
Even I increment counter 1 and the text changes to odd increment again and it toggles between odd and even if increment counter 2 on the other hand you can see that the text remains unaffected now let’s take our example to the next level at the moment we have a
Simple is even function which takes hardly any time to execute in real world applications though he will sometimes come across logic that takes considerable amount of time for execution that is a function that isn’t so good with performance it could be for example fetching thousands of items mapping that array filtering that array
And even sorting that array now we don’t really have the kind of logic here so let’s induce some slowness into our function so within the is even function need to declare a variable let I is equal to 0 and then add a while loop that simply iterates for a long time so
While I is less than 2 followed by 9 zeros you’re simply going to increment I so I plus plus so the loop doesn’t really effect a return value but it does slow down the rate at which we compute where the counter 1 is odd or even now
Let’s save the file and see what happens in the browser to start off we have initial count set to zero for both the counters I click on increment counter 1 and you can see that there is now a second or two delay before the UI updates I’ll click again
So watch closely see that a UI is slow in updating and this is because in the UI we are rendering whether the number is art or even and that logic is from the east even function which as it turns out is really slow and this of course is
Expected if the number changes react needs to check if the new number is odd or even but take a look at this I now click on increment to and still there is a delay with the UI updates watch closely I click and after a second or two counter two increments this is strange
Though isn’t dead why is counter too slow as well well that is because every time the state updates the component re-renders and when the componentry renders these even function is called again the function is slow and hence even when we update counter to the UI
Update is slow so what we need is a way to tell react not to recalculate certain values when unnecessary especially the ones which take a long time to compute in our example we need to tell react not to calculate whether counter one is odd or even when we are changing counter two values
This is where the use memmer hook comes into picture yes memo is a hook that will only recompute the cached value when one of the dependencies has changed this optimisation heads to avoid expensive calculations on every render the way you use memo works is very similar to how
Use callback works first import use memo from react next win the component call the use memo hook as the first argument we pass in the function whose return value needs to be cashed in our example this would be the arrow function to calculate if a number
Is odd or even I’m going to cut this arrow function and paste it as the first argument as a second parameter we need to specify the dependencies our function depends on the value of counter one that is whenever counter one changes we are telling react to recompute the value and
Not use the cached value so in the array specify counter one use memo returns a cached value which we are going to assign to the variable is even finally in the JSX I’m going to remove the parenthesis is even is not going to be a function call
Because it now stores a value all right let’s save the file and test it out I’m going to click on counter one and you can see that the delay is still present now that is because we need to recalculate is odd or even when the value changes when I click on counter to
However you can see that the updates are way faster this is because react is now using the cached value of is even function to display where the count 1 is odd or even since the value never changed for counter 1 there is no need to recompute this odd or even value
React will simply use the cached value from the previous render this is how use memo hook can be used for performance optimization now if I go back to the code you might feel that use call back and use memo are very similar what is the difference but the
Difference is that use callback caches the provided function instance itself whereas use memo invokes the provided function and caches its result so if you need to cash a function use callback and when you need to cache the result of an invoked function use memo alright that is about use callback use memo and
Performance optimization with hooks thank you guys for watching feel free to 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
Thank you brother, It is so great. You explain everything very slowly and amazingly. Awesome bro.
Keep it Please. 😁
why don't more tutors explain like this???? you sir are a hero
Awesome
easiest and shorted explanation on whole youtube, thanks
Thank you for your nice presentation. I understand this topic. 🙂
I think finally I am clear with useMemo and useCallback, but definitely optimization is advance skills in react. I am glad to achieve it
even paid courses dont teach this well..
great
Well done bro. Very informative. I have one question. What about memorizing a component and passing an equality check function to use Memo as 2nd argument?
If you could also put some light on this, that would be really great.
The comment in the last 20 seconds of the video gets my sub! Amazing coverage of this topic!
In this particular case, can the delay be reduced without changing the 1st parameter (i.e. function) of useMemo?
You are superb ❤❤
Thanks a lot Sir you explained it way better that I can understand easily…
what is the difference between useEffect and useMemo. Anyone please let me know.
Best and easy to capture explanation
Amazing. You are the best!
What is cached value ?
Best tutorial 🔥
Simply the best explanation on hooks
Loved your video
Way to go brother…
thank you
I know React is wanted by many, but let's be fair that a good number of these hooks and techniques are created merely to somehow patch deficiencies in the React core design!
Thanks for those videos.
how to type triple equal to and triple not equal to in vs code
thank you as always , simple and straight forward
How to write that equal to 3:29
Awesome man
Wow awesome
Thank you so much sir ❤️
Good explanation
will the useEffect with counterOne as dependency work to compute isEven state. Like an alternative to useMemo
Yeah, this is probably the best explanation of useMemo on the internet. Bravissimo, sir!
looking for this exact example…….
Awesome
Both useMemo and useCallback use memoization.
I like to think of memoization as remembering something.
While both useMemo and useCallback remember something between renders until the dependancies change, the difference is just what they remember.
useMemo will remember the returned value from your function.
useCallback will remember your actual function
Source:StackOverflow……
so comparing the example from previous video
useCallback:
const incrementSalary = useCallback(() => {
setSalary(salary + 1000);
}, [salary]);
useMemo:
const isEven = useMemo(() => {
let i = 0;
while (i < 200000000) i++;
return countOne % 2 === 0;
}, [countOne])
see,useCallback retun function and useMemo return value
it helped me a lot,
Your every example is awesome, clear
How to the same in class components??
Can someone please help me
Nice explanation but i have a question you converted even function to "value" to be returned but what if "even" function logic depends on "some parameters being passed from child" and it has to remain as function && this function can be utilized by many childs and can return the value as per the passed paramamters from child. what do we use then useCallback or useMemo. i am bit confused please help me.
nicely explained
could we use the useeffect adding dependecies to achieve same like what usememo does?
Best Explaination
u are the best ever <3
Finally, a simple explanation that goes beyond just reading and demonstrating what is already in the docs. Thanks!
Wouldn't this problem be solved if u used useCallback too?
Amazing explanation!! I am finally starting to understand concepts that have been eluding me for some time. Your tutorials are AWESOME!!!
const incrementAge = useCallback(() => setAge((age) => age + 1), []);
const incrementSalary = useCallback(() => setSalary(salary + 1000), [salary]);
This also works based on the knowledge from your earlier tutorials.
👍👍👍
Thanks 🤩🤩