Comments (4)
You can use a ref callback, something like this:
(see https://codesandbox.io/s/244jl7o300)
const arr = new Array(1000).fill().map((_, i) => i);
function App() {
const [pos, setPos] = useState(0);
const [element, setElement] = useState(null);
useEventListener('scroll', ev => setPos(ev.target.scrollTop), element);
return (
<div>
<div className="scroll" ref={el => setElement(el)}>
{arr.map(i => (
<div key={i}>{i}</div>
))}
</div>
<div>Scroll position: {pos}</div>
</div>
);
}
from use-event-listener.
Thank, it works !!
from use-event-listener.
Thanks for writing this library. I've found the binding and un-binding of event listeners to refs to be a bit non-intuitive to catch all the edge cases and have found this really useful.
I am trying to understand the logic behind all of this. If you get some time could you please let me know if the following sounds correct to you?
-
You are using a callback ref here because you are only guaranteed to be notified about a ref being updated when using a callback ref, not a regular ref. From Hooks API Reference - useRef:
Keep in mind that useRef doesn’t notify you when its content changes. Mutating the .current property doesn’t cause a re-render. If you want to run some code when React attaches or detaches a ref to a DOM node, you may want to use a callback ref instead.
So if you had used a regular ref it could potentially have been updated and we might not have bound to the new element.
-
When the ref changes you store that outcome in a state variable. This is done to ensure that a re-render is triggered when the ref changes. That re-render ensures that the second
useEffect
insideuseEventListener
triggers, which will un-bind the old event listener from the old element and bind a new event listener to the new element. And the un-binding all works correctly because the clean-up function returned fromuseEffect
captures the originalelement
value in a closure.
from use-event-listener.
Just for anyone landing here, the answer of using a ref callback to solve this issue can be made slightly more efficient:
return (
<div>
<div className="scroll" ref={setElement}> // <-- no inline function here
{arr.map((i) => (
<div key={i}>{i}</div>
))}
</div>
<div>Scroll position: {pos}</div>
</div>
);
Codesandbox
This prevents an extra render when the component gets re-rendered.
from use-event-listener.
Related Issues (19)
- How to add listener for particular group of DOM Elements? HOT 3
- Feature request: have more specific parameter typings
- Hook doesn't allow `element` to be null HOT 1
- add all-contributors HOT 2
- Discuss design decision of underlying implementation HOT 2
- TypeScript definitions in repo do not match with latest version on npm HOT 4
- [Question] Please show example how create another hook based on that HOT 1
- Only start listener after some condition? HOT 8
- Support for event listener options HOT 4
- Do not work, If we pass element as ref HOT 9
- Republish the package with updated peerDependencies 'cause now we have a problem for React 17 HOT 5
- adding duplicate events HOT 1
- Removing event listener HOT 2
- eslint conditional issue
- Saving handler in useEffect() HOT 1
- does not work with chrome.runtime.onMessage
- How to prevent event propagation / bubbling? HOT 1
- Is useEffect necessary to update the ref? (genuine question) HOT 2
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from use-event-listener.