diff --git a/example.js b/example.js
index 62d641b..a7380c9 100644
--- a/example.js
+++ b/example.js
@@ -3,8 +3,12 @@ import { render } from 'react-dom';
import useWindowWidth from './';
function App() {
+ let debouncedWindowWidth = useWindowWidth(500);
let windowWidth = useWindowWidth();
- return
{JSON.stringify(windowWidth)}
;
+ return [
+ Debounced: {JSON.stringify(debouncedWindowWidth)}
,
+ Firehose: {JSON.stringify(windowWidth)}
,
+ ];
}
render(, window.root);
diff --git a/index.js b/index.js
index effa201..e266f6a 100644
--- a/index.js
+++ b/index.js
@@ -1,4 +1,4 @@
-'use strict';
+'use strict'
let { useState, useEffect } = require('react');
function getSize() {
@@ -8,13 +8,21 @@ function getSize() {
outerHeight: window.outerHeight,
outerWidth: window.outerWidth,
};
-}
+};
-function useWindowSize() {
+function useWindowSize(debounceMs) {
let [windowSize, setWindowSize] = useState(getSize());
+ let timeoutId;
+
function handleResize() {
- setWindowSize(getSize());
+ if (timeoutId) {
+ clearTimeout(timeoutId);
+ }
+
+ timeoutId = setTimeout(function() {
+ setWindowSize(getSize());
+ }, debounceMs);
}
useEffect(() => {
diff --git a/package.json b/package.json
index 7d0e966..42a755c 100644
--- a/package.json
+++ b/package.json
@@ -39,4 +39,4 @@
"./test-setup.js"
]
}
-}
+}
\ No newline at end of file