react-use-listener
v1.0.2
Published
attach native event without and don't care about bind / unbind
Downloads
1,507
Maintainers
Readme
useListener
attach native event without and don't care about bind / unbind
Demo CodeSandbox
Usage
- bind resize event
import {useState} from "react";
function App() {
const [width, setWidth] = useState(0)
useListener(window, "resize", () => {
setWidth(window.innerWidth);
});
return (
<div>Width: {width}</div>
)
}
- cancel binding
import {useState} from "react";
function App() {
const [width, setWidth] = useState(0)
const listener = useListener(window, "resize", () => {
setWidth(window.innerWidth);
if (window.innerWidth < 1000) {
listener();
}
});
return (
<div>Width: {width}</div>
)
}
- conditionally bind event
import {useState} from "react";
function App() {
const [enabled, setEnabled] = useState(false);
const [width, setWidth] = useState(0)
useListener(window, "resize", () => {
setWidth(window.innerWidth);
}, {
enabled
});
return (
<div>
<div>Width: {width}</div>
<button onClick={() => setEnabled(!enabled)}>Bind resize</button>
</div>
)
}
- debounce
import {useState, useRef} from "react";
function App() {
const ref = useRef();
useListener(ref, "keyup", (e) => {
// set width after 300 milliseconds when stopped resizing
console.log(e.target.value);
}, {
debounce: 300
});
return (
<div>
<input ref={ref} />
</div>
)
}
- throttle
import {useState} from "react";
function App() {
const [width, setWidth] = useState(0)
useListener(window, "resize", () => {
// trigger after 300 milliseconds
setWidth(window.innerWidth);
}, {
throttle: 300
});
return (
<div>
<div>Width: {width}</div>
</div>
)
}
Reference
const listener = useListener(element, event, callback, option);
element
: Element | Document | Window | ref
element to attache eventevent
: string
event name to bindcallback
: (e) => void
callbackoption
:enabled
: boolean
weather to listen or not, defaulttrue
throttle
: number
to throttle event, defaultundefined
debounce
: number
debounce event, defaultundefined
capture
: boolean
native flagpassive
: boolean
native flagonce
: boolean
native flag