Skip to content

Commit

Permalink
feat: add onChange callback to useWindowSize
Browse files Browse the repository at this point in the history
  • Loading branch information
mahmoud-elgammal committed Dec 2, 2024
1 parent 3eb531a commit ea656f7
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 6 deletions.
18 changes: 13 additions & 5 deletions src/useWindowSize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,44 +3,52 @@ import { useEffect } from 'react';
import useRafState from './useRafState';
import { isBrowser, off, on } from './misc/util';

// Define the type for options that can be passed to the hook
interface Options {
initialWidth?: number;
initialHeight?: number;
onChange?: (width: number, height: number) => void;
initialWidth?: number; // Initial width of the window (Default value is Infinity)
initialHeight?: number; // Initial height of the window (Default value is Infinity)
onChange?: (width: number, height: number) => void; // Callback function to execute on window resize (optional)
}

const useWindowSize = ({
initialWidth = Infinity,
initialHeight = Infinity,
onChange,
}: Options = {}) => {
// Use the useRafState hook to maintain the current window size (width and height)
const [state, setState] = useRafState<{ width: number; height: number }>({
width: isBrowser ? window.innerWidth : initialWidth,
height: isBrowser ? window.innerHeight : initialHeight,
});

useEffect((): (() => void) | void => {
// Only run the effect on the browser (to avoid issues with SSR)
if (isBrowser) {
const handler = () => {
const width = window.innerWidth;
const height = window.innerHeight;

// Update the state with the new window size
setState({
width: window.innerWidth,
height: window.innerHeight,
width,
height,
});

// If an onChange callback is provided, call it with the new dimensions
if (onChange) onChange(width, height);
};

// Add event listener for the resize event
on(window, 'resize', handler);

// Cleanup function to remove the event listener when the component is unmounted (it's for performance optimization)
return () => {
off(window, 'resize', handler);
};
}
}, []);

// Return the current window size (width and height)
return state;
};

Expand Down
6 changes: 5 additions & 1 deletion stories/useWindowSize.story.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
import { storiesOf } from '@storybook/react';
import * as React from 'react';
import { useWindowSize } from '../src';
import { action } from '@storybook/addon-actions'; // Import addon-actions
import ShowDocs from './util/ShowDocs';

const Demo = () => {
const { width, height } = useWindowSize();
const { width, height } = useWindowSize({
// Log the resize event to the Storybook actions panel
onChange: action('window resize'),
});

return (
<div>
Expand Down

0 comments on commit ea656f7

Please sign in to comment.