Create the hook to register native event like window.addEventListener, and cleanup (remove) automatically.
$ npm install create-event-target-hook
If you have use some native event in React, the cleanup show in below is really common
//useCustom
useEffect(() => {
function cb1() {
console.log('click');
}
function cb2() {
console.log('resize');
}
function cb3() {
console.log('touch');
}
window.addEventListener('click', cb1);
window.addEventListener('resize', cb2);
window.addEventListener('touch', cb3);
return () => {
window.removeEventListener('click', cb1);
window.removeEventListener('resize', cb2);
window.removeEventListener('touch', cb3);
};
},[]);
const useWindow = createEventTargetHook(window);
//useCustom
useWindow('click', () => console.log('click'));
useWindow('resize', () => console.log('resize'));
useWindow('touch', () => console.log('touch'));
-
I create a curry function, and make a corresponding custom hooks
-
Only
addEventListener
when mount, I promise. -
I keep a reference of the annoymous callback, so I can remove the annoymous listener.
-
The function of cleaning the event listener will follow the hook life-cycle.
This customHooks will return an array
We assume useImage
has already made. (by createEventTargetHook
)
const [$img, loadOff] = useImage('load', () => console.log('load'));
$img
is the EventTarget, sometimes we hope we could modify its attribute.
You can use off to remove listener.
- Remove the event listener initiative.
const [$img, off] = useImg('xxx', () => {});
// In some condition
{
off();
}
- Remove when something done.
import createEventTargetHook from 'create-event-target-hook';
const useImage = createEventTargetHook(new Image());
const demo = () => {
const [$img, loadOff] = useImage('load', getSize);
function getSize() {
loadOff();
}
return <button onClick={onClick}> Get Image </button>;
};
import createEventTargetHook from 'create-event-target-hook';
const useFileReader = createEventTargetHook(new FileReader());
const demo = () => {
const [$reader, offEvent] = useFileReader('loadend', () =>
console.log('load end')
);
const onInputChange = e => {
const files = e.currentTarget.files;
$reader.readAsDataURL(files[0]);
};
return (
<input
onChange={onInputChange}
type="file"
id="upload-file"
placeholder="Upload a Picture"
/>
);
};