React component for auto adding/removing event listeners during component life cycle.
npm
npm install react-domlistener
yarn
yarn add react-domlistener
This project exports a component, DOMListener
, which serves the purpose of auto adding/removing an event listener during the life cycle of a React component. One of the advantages to using this component over manually using addEventListener
/removeEventListener
yourself is that you don't have to worry about cases where you forget to remove. When forgetting to remove event listeners you create memory leaks, which can be difficult to track down.
Below is an example of how to use react-domlistener.
import {DOMListener} from 'react-domlistener'
export default class FooBar extends React.Component {
_handleWindowResize = (e) => {
// TODO: do something clever on window resize
}
render() {
return (
<div className="foo-bar">
<DOMListener
listener={this._handleWindowResize}
target={window}
type="resize"
/>
</div>
)
}
}
NOTE: This project requires at a minimum React version 16.3.0 as it depends on newer API methods introduced in this version.
Please see the code of conduct.
Please see the contributing guide.