Open mnzaki opened 4 years ago
ALSO full disclosure, I have not properly (SCIENCE) checked if my theory makes sense :D It's on the road map though.... to one day install and use https://github.com/welldone-software/why-did-you-render
Hey Mina, thank you for sharing this. The library you shared is an amazing resource.
You are right about optimization, there could be further optimization done inside the QuestionCard
component. Indeed we can wrap onSubmitAnwer
function (that I passed to OptionBtn
component) in useCallback
- it will prevent function re-creation on every re-render of QuestionCard
component. As well as getting rid of inline styles will help in the optimization.
On another rerendering note, I think
<QuestionCard>
or parts of it would keep rerendering for another reason:useCallback
!I'm not familiar with this very much, but based on their docs https://reactjs.org/docs/hooks-reference.html#usecallback
useCallback
creates memoized callbackuseCallback(fn, deps)
is equivalent touseMemo(() => fn, deps)
I believe the point is to use the returned memoized callback directly without wrapping it into another function, because then the memoization becomes useless, since you would be creating another function every time anyway!
I mean to say that doing something like the following:
would void the benefits of memoization.
If
myPureComp
is rerendered (because parent is rerendered, or whatever), then<Button>
will also be rerendered always! This is because theonClick
value is actually a fresh function every time.I believe it's meant instead to be used like
<Button onClick={cb} />
And of course this gets tricky if you have to pass a closured variable as a parameter to the memoized callback :D which is what happens in<QuestionCard>
!I'm playing around with some ways to solve this, but right now I'm more interested in actually using Context Providers to solve a major issue we have been facing with AppWrap functionality! (it's a wrapper that all components use to control global things.... long story that spans React Native versions....)