UseMemo Hook in React?
What is Use Memo Hook in React ?
Use memo hook in react is used to memoized the result of the function which contains the expensive calculation , that does not causes slow down of the component so we wrap the function in the useMemo hook
Whenever the function runs on the initial render , useMemo runs the function and calculate the value of the function but when the component re-renders , if from the dependency list none of the dependency changed , it will just used the cached value of the result and will not calculate in re-render.
UseMemo is very useful and we can also memoized any data from the component , not just the functions we can memoized any object or data .
Although , useMemo is particularly for the expensive calculation in functions.
Let's see an example , how to use UseMemo hook in reality?
How to use UseMemo Hook in react?
UseMemo hook is a function and takes the function as a first parameter , it wraps the function and stores into it and in the second parameter we list the dependencies to which our function will depend on.
We can also write the useMemo hook for the initial render , just by writing the empty list of dependencies , on every render and when some state or value changes.
Whenever some dependency changed the useMemo hook re-calculates the function and cache the result , and use the cache result if none of the dependency has changed
In the above example , we set up the expensive function in heavy calculation is done by this function our component is slow down and the button take some milliseconds to update the state , and we are also displaying the values in the web browser so we can do the analysis .
Now , we will wrap the function into the useMemo hook and set up the dependency for the useMemo to depend ,which can ensure to only re-calculate the value when count value changes and until then uses the cache result of the function.
This is how useMemo saves us from unnecessary re-calculation of heavy functions and prevents our components to slow down by memoized the result of the function.
I hope this can clear your understanding with useMemo hook and will also share the code Sandbox link below.
Thank you for reading this blog post!
Comments
Post a Comment