File tree Expand file tree Collapse file tree 1 file changed +34
-1
lines changed
Expand file tree Collapse file tree 1 file changed +34
-1
lines changed Original file line number Diff line number Diff line change 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
3568Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
3669
You can’t perform that action at this time.
0 commit comments