Optimization may overkill Performance (React)
varunprashar5
Posted on September 2, 2021
๐๐๐ป๐ถ๐ผ๐ฟ ๐๐ฒ๐: ๐ช๐ฒ ๐๐ต๐ผ๐๐น๐ฑ ๐๐ฟ๐ฎ๐ฝ ๐ฒ๐๐ฒ๐ฟ๐ ๐ณ๐๐ป๐ฐ๐๐ถ๐ผ๐ป ๐ถ๐ป๐๐ถ๐ฑ๐ฒ "๐๐๐ฒ๐๐ฎ๐น๐น๐ฏ๐ฎ๐ฐ๐ธ" ๐ต๐ผ๐ผ๐ธ ๐๐ผ ๐ฏ๐ผ๐ผ๐๐ ๐ฝ๐ฒ๐ฟ๐ณ๐ผ๐ฟ๐บ๐ฎ๐ป๐ฐ๐ฒ.
๐ฆ๐ฒ๐ป๐ถ๐ผ๐ฟ ๐๐ฒ๐: ๐ฆ๐ฒ๐ฟ๐ถ๐ผ๐๐๐น๐ (๐/๐ ๐ฐ๐ต๐ฒ๐ฐ๐ธ๐ถ๐ป๐ด ๐ฝ๐ฟ๐ผ๐ณ๐ถ๐น๐ถ๐ป๐ด)? ๐ ๐๐ต๐ถ๐ป๐ธ ๐ถ๐ ๐๐ถ๐น๐น ๐ฏ๐ฒ ๐ฎ ๐ฝ๐ฒ๐ฟ๐ณ๐ผ๐ฟ๐บ๐ฎ๐ป๐ฐ๐ฒ ๐ธ๐ถ๐น๐น!
^ ^ In continuation to the last post (React.memo):
When a component gets a function as a prop from its parent, then whenever a parent is rendered, its child component will get re-rendered every time no matter even if you have used React.memo().
Do checkout the video for more details:
https://youtu.be/5aH_b5pUAHI
<๐๐ถ๐ด๐๐ถ๐๐ ๐ถ๐๐ฒ๐บ๐={๐ถ๐๐ฒ๐บ๐} ๐ถ๐๐ฒ๐บ๐๐น๐ถ๐ฐ๐ธ={๐ถ๐๐ฒ๐บ๐๐น๐ถ๐ฐ๐ธ} />
In above line, even if is passed via React.memo, It will still re-render because itemClick function will get re-created every time the parent component is rendered.
๐ ๐ต๐ฎ๐๐ฒ๐ป'๐ ๐ฐ๐ต๐ฎ๐ป๐ด๐ฒ๐ฑ ๐๐ต๐ฒ ๐ณ๐๐ป๐ฐ๐๐ถ๐ผ๐ป, ๐ฏ๐๐ ๐๐ต๐ ๐๐ถ๐น๐น ๐ถ๐ ๐๐๐ถ๐น๐น ๐ฟ๐ฒ-๐ฟ๐ฒ๐ป๐ฑ๐ฒ๐ฟ?
This is how Javascript works, you should know that two references are never equal.
[1,2] === [1,2] //false
1==1 //true (primitives are equal)
Primitive values will be the same on every re-render but objects will be different (functions are objects in Javascript).
To prevent this, just wrap your function with useCallback hook.
๐๐๐ฒ๐๐ฎ๐น๐น๐ฏ๐ฎ๐ฐ๐ธ(๐ณ๐๐ป๐ฐ๐๐ถ๐ผ๐ป, [๐ฑ๐ฒ๐ฝ๐ฒ๐ป๐ฑ๐ฒ๐ป๐ฐ๐ถ๐ฒ๐])
//Here we are saying to use the same function on re-renders
//If you pass an array of dependencies, then whenever any of the dependencies change, then a new function will be used.
๐๐ผ๐ฒ๐ ๐ถ๐ ๐บ๐ฒ๐ฎ๐ป ๐๐ต๐ฎ๐ ๐ ๐๐ต๐ผ๐๐น๐ฑ ๐๐ฟ๐ฎ๐ฝ ๐ฒ๐๐ฒ๐ฟ๐ ๐ณ๐๐ป๐ฐ๐๐ถ๐ผ๐ป ๐ถ๐ป๐๐ถ๐ฑ๐ฒ ๐บ๐ ๐ฐ๐ผ๐บ๐ฝ๐ผ๐ป๐ฒ๐ป๐ ๐๐ถ๐๐ต ๐๐๐ฒ๐๐ฎ๐น๐น๐ฏ๐ฎ๐ฐ๐ธ?
You should ๐ก๐๐ฉ๐๐ฅ do that, Here are the reasons:
Optimisation always does come with a cost, it's a special function that will never be garbage collected and will always have a reference in the memory.
Extra check for the different values in the array of dependencies to see if these dependencies are changed then they have to recreate the newer function.
Donโt forget that useCallback() hook is called every time the parent component renders. Even useCallback() returns the same function object, still the inline function is re-created on every re-rendering (useCallback() just skips it).
๐๐ผ๐ ๐๐ผ ๐ฑ๐ฒ๐ฐ๐ถ๐ฑ๐ฒ ๐๐ต๐ฒ๐๐ต๐ฒ๐ฟ ๐๐ผ ๐๐๐ฒ ๐๐๐ฒ๐๐ฎ๐น๐น๐ฏ๐ฎ๐ฐ๐ธ() ๐ผ๐ฟ ๐ป๐ผ๐?
There will never be a single answer to this problem, So always run your profiler and see what performance gain you will get and then decide.
Posted on September 2, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 18, 2024