Q: should we use useCallback on native HTML elements
See original GitHub issueDo you want to request a feature or report a bug?
It’s a question.
What is the current behavior?
According to the docs, this could be useful optimizing callback functions being passed down:
This is useful when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders (e.g.
shouldComponentUpdate
).
My question is: should we use useCallback
when passing a callback to a native HTML element? e.g. <button onClick={callback}></button>
Issue Analytics
- State:
- Created 4 years ago
- Reactions:2
- Comments:11 (1 by maintainers)
Top Results From Across the Web
When to use React.useCallback() | Ahead Creative
To recap, useCallback is a React Hook which returns a memoized version of the callback function it is passed. This means that the...
Read more >useCallback and useRef: Two React Hooks You Should Learn
Learn how to use the useCallback hook to avoid unnecessary re-renders in our application, and the useRef hook to keep track of references....
Read more >Understanding useMemo and useCallback - Josh W Comeau
Fundamentally, useMemo and useCallback are tools built to help us optimize re-renders. They do this in two ways: Reducing the amount of work ......
Read more >Should we use useCallback in every function handler in React ...
The short answer is because arrow function is recreated every time, which will hurt the performance. This is a common misconception.
Read more >How to use useCallback() hook - Medium
useCallback(callback, dependencies) can be used like useMemo() , but it memoizes functions instead of values, to prevent recreation upon every ...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Doesn’t really specifically relate, but yes, that’s part of what’s going on here. React has its one single event listener at the root of the component tree, and is (I assume) just storing something like
eventListeners[elementKey].onClick = element.props.onClick
(totally fake code).No, there’s no benefit for that.
The point of
useCallback
is to create a consistent reference for a callback function. This primarily matters if you are passing it to a child component that is attempting to optimize re-renders based on whether its props have changed by reference (ie,PureComponent
andReact.memo()
).A plain HTML element does not care if you are passing in a different click handler reference each time, so there’s no benefit in this situation.