I am a fan of React/hooks. As the usage scenarios in business projects gradually increase, I find the useCallback/useMemo hooks are a bit annoying. Whenever I use components developed by others, when I need to pass function props, I will wrap it with useCallback first. It might actually work fine without the packaging.
This can be divided into two cases, one is to avoid unnecessary re-render, and the other is to ensure the correctness of the logic. For example, useEffect depends on the incoming function props. Using too many useCallback/useMemo will make the code look bloated, and if you don't use it, you may be worried about bugs.
I learned what some developers in the community think:
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. from kent C. Dodds.
I would like to ask the community if there are any suggestions for using useCallback/useMemo. It can reduce the mental burden when writing code. For example, is it possible to agree that useCallback/useMemo is usually not needed in the code? If it needs to be used, the component should be clearly stated, such as adding comments to props and so on.
Top comments (1)
I agree with the view that functions (with/without props) used in components, in general, should be wrapped in a
useCallback
function if only you intend to prevent unnecessary re-renders as you've mentioned. However there are some exceptions, if say, it won't lead to much significant performance.As the developer, how would you know that?
Therefore, I think that this then comes down to on behalf of the developer to use their "programming wisdom" to either include it or not.
BTW: Adding comments to suggest the developer who wishes to use such function props is not so much of a bad idea :¬)