I am recently refactoring a web app using React Hooks. I encounter a problem regarding useCallback
. Based on description of Kent: https://kentcdodds.com/blog/usememo-and-usecallback, useCallback
is to pass in identical function reference to sub-components, to avoid re-render of sub-components, so that the performance is better. However, it's used together with React.memo
. And as Kent said:
MOST OF THE TIME YOU SHOULD NOT BOTHER OPTIMIZING UNNECESSARY RERENDERS. React is VERY fast and there are so many things I can think of for you to do with your time that would be better than optimizing things like this. In fact, the need to optimize stuff with what I'm about to show you is so rare that I've literally never needed to do it ...
So, my question is: am I right to claim that we do not need to use useCallback
usually? except when the callback is expensive to create, using useCallback
avoids re-creating the callback for every render.
Say, for a onClick
or onChange
event handler, 2 lines or less, shall we just not use useCallback
to wrap it?
it can be tricky to get right all the time so you may not be reaping any benefits at all anyway.
So in other words; "it's difficult so don't bother". I do agree that it is difficult but gets a lot easier when you define containers / presentational components and use selectors in your containers (as you should already anyway). – Shaft