react-use-listener
Advanced tools
attach native event without and don't care about bind / unbind
Weekly downloads
Readme
attach native event without and don't care about bind / unbind
Demo CodeSandbox
import {useState} from "react";
function App() {
const [width, setWidth] = useState(0)
useListener(window, "resize", () => {
setWidth(window.innerWidth);
});
return (
<div>Width: {width}</div>
)
}
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>
)
}
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>
)
}
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>
)
}
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>
)
}
const listener = useListener(element, event, callback, option);
element
: Element | Document | Window | ref
element to attache event
event
: string
event name to bind
callback
: (e) => void
callback
option
:
enabled
: boolean
weather to listen or not, default true
throttle
: number
to throttle event, default undefined
debounce
: number
debounce event, default undefined
capture
: boolean
native flagpassive
: boolean
native flagonce
: boolean
native flagattach native event without and don't care about bind / unbind
The npm package react-use-listener receives a total of 202 weekly downloads. As such, react-use-listener popularity was classified as not popular.
We found that react-use-listener demonstrated a healthy version release cadence and project activity. It has 1 open source maintainer collaborating on the project.