Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion example.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,12 @@ import { render } from 'react-dom';
import useWindowWidth from './';

function App() {
let debouncedWindowWidth = useWindowWidth(500);
let windowWidth = useWindowWidth();
return <pre>{JSON.stringify(windowWidth)}</pre>;
return [
<pre>Debounced: {JSON.stringify(debouncedWindowWidth)}</pre>,
<pre>Firehose: {JSON.stringify(windowWidth)}</pre>,
];
}

render(<App />, window.root);
16 changes: 12 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
'use strict';
'use strict'
let { useState, useEffect } = require('react');

function getSize() {
Expand All @@ -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(() => {
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,4 +39,4 @@
"./test-setup.js"
]
}
}
}