Skip to content

Commit f749445

Browse files
committed
UPDATE: Readme.md
Signed-off-by: dziksu <benjaminrast93@gmail.com>
1 parent 09ecfd0 commit f749445

File tree

1 file changed

+34
-1
lines changed

1 file changed

+34
-1
lines changed

README.md

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# React hook use-window-width
22

3-
React a simple hook to receive current window width using window.requestAnimationFrame for a great performance.
3+
A simple hook for React to receive current window width using `window.requestAnimationFrame` for a better performance.
44

55
## Installation
66

@@ -31,6 +31,39 @@ const MyComponnet: React.FC = () => {
3131
};
3232
```
3333

34+
## RAW implementation
35+
If you don't want to use the package, and you only need a simple hook implementation you can just copy and paste the current implementation from `/src/index.tsx`
36+
37+
```typescript jsx
38+
import { useCallback, useEffect, useRef, useState } from 'react';
39+
40+
function useWindowWidth(): number {
41+
const isMounted = useRef<boolean>(true);
42+
const isSsr = typeof window === 'undefined';
43+
const [width, setWidth] = useState(isSsr ? 0 : window.innerWidth);
44+
45+
const handleResize = useCallback(() => {
46+
if (isMounted.current) {
47+
setWidth(window.innerWidth);
48+
}
49+
}, [setWidth]);
50+
51+
useEffect(() => {
52+
window.addEventListener('resize', () => {
53+
window.requestAnimationFrame(handleResize);
54+
});
55+
return () => {
56+
isMounted.current = false;
57+
window.removeEventListener('resize', handleResize);
58+
};
59+
}, [handleResize]);
60+
61+
return width;
62+
}
63+
64+
export default useWindowWidth;
65+
```
66+
3467
## Contributing
3568
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
3669

0 commit comments

Comments
 (0)