3 ms·
Isn't useCallback to solve the common mistake of: <button onClick={() => setText("clicked")}>click</button> Without useCallback this would update the dom on e
by acover 4y ago
Isn't useCallback to solve the common mistake of:
<button onClick={() => setText("clicked")}>click</button>
Without useCallback this would update the dom on every render.
- littlecranky67 4y agoUnfortunately the "update on every render" is deeply anchored into devs minds, although in most cases play a minor role. It comes back from a time where browser JS engines where really slow to create lambdas - which is not the case anymore. Additionally, react doesn't really update the DOM on "render" (the internal react render cycle) - due to DOM diffing. My best advice is (also apart from React): Do not spend time on imagined/anticipated performance bottlenecks; only ever spend time on performance tuning if there are real (perceived, not measurable!) performance issues (there has to be a profiling report in your hand).
- acover 4y agoYeah I only started caring about this when tracking down lag in my app. Though it's fun to think about :) I believe this causes a real Dom update because it can't know the onclick function hasn't materially changed. It's just diffing function references.
- graftak 4y agoThe main use for useCallback is to add a callback to a useEffect dependency array without it running on every render.
- darepublic 4y agoThat's not a mistake lol.
- acover 4y agoCan you explain why it isn't? I'm probably misunderstanding something. setText doesn't change because it's from useState. The only reason to update the Dom is because the onclick function isn't memoized. Updating the Dom every render isn't terrible but it isn't good.
- darepublic 4y agobutton is just a small lightweight element usually with a single string child. If passing a lightweight unwrapped click handler to a leaf node is a faux pas then honestly the react team needs to memoize by default. Your description "updating the dom every render..." And acting like indiscriminate useCallback is a panacea for your performance problems to me seems like a pretty naive take. But then again seems like the community opinion in this has shifted, I just honestly don't get it. And I do use useCallback btw, but only when I need to keep referential stability for known reasons,not as an automatic default