Add onWindow hooks

This commit is contained in:
Chalarangelo
2021-11-08 15:52:33 +02:00
parent 0043ec2e18
commit e76941f2f1
2 changed files with 72 additions and 0 deletions

View File

@ -0,0 +1,37 @@
---
title: useOnWindowResize
tags: hooks,effect,intermediate
firstSeen: 2021-12-01T05:00:00-04:00
---
Executes a callback whenever the window is resized.
- Use the `useRef()` hook to create a variable, `listener`, which will hold the listener reference.
- Use the `useEffect()` hook and `EventTarget.addEventListener()` to listen to the `'resize'` event of the `window` global object.
- Use `EventTarget.removeEventListener()` to remove any existing listeners and clean up when the component unmounts.
```jsx
const useOnWindowResize = callback => {
const listener = React.useRef(null);
React.useEffect(() => {
if (listener.current)
window.removeEventListener('resize', listener.current);
listener.current = window.addEventListener('resize', callback);
return () => {
window.removeEventListener('resize', listener.current);
};
}, [callback]);
};
```
```jsx
const App = () => {
useOnWindowResize(() =>
console.log(`window size: (${window.innerWidth}, ${window.innerHeight})`)
);
return <p>Resize the window and check the console</p>;
};
ReactDOM.render(<App />, document.getElementById('root'));
```

View File

@ -0,0 +1,35 @@
---
title: useOnWindowScroll
tags: hooks,effect,intermediate
firstSeen: 2021-12-08T05:00:00-04:00
---
Executes a callback whenever the window is scrolled.
- Use the `useRef()` hook to create a variable, `listener`, which will hold the listener reference.
- Use the `useEffect()` hook and `EventTarget.addEventListener()` to listen to the `'scroll'` event of the `window` global object.
- Use `EventTarget.removeEventListener()` to remove any existing listeners and clean up when the component unmounts.
```jsx
const useOnWindowScroll = callback => {
const listener = React.useRef(null);
React.useEffect(() => {
if (listener.current)
window.removeEventListener('scroll', listener.current);
listener.current = window.addEventListener('scroll', callback);
return () => {
window.removeEventListener('scroll', listener.current);
};
}, [callback]);
};
```
```jsx
const App = () => {
useOnWindowScroll(() => console.log(`scroll Y: ${window.pageYOffset}`));
return <p style={{ height: '300vh' }}>Scroll and check the console</p>;
};
ReactDOM.render(<App />, document.getElementById('root'));
```