Skip to content

Instantly share code, notes, and snippets.

@luisvinicius09
Last active December 22, 2022 22:31
Show Gist options
  • Save luisvinicius09/78dfb5cafb77b3e10afffe03a0d9ee1e to your computer and use it in GitHub Desktop.
Save luisvinicius09/78dfb5cafb77b3e10afffe03a0d9ee1e to your computer and use it in GitHub Desktop.
useWindow react hook
import { useState, useEffect, useRef } from 'react';
/**
* Generated by
* @link - https://chat.openai.com
*
* React hook to access the window object.
* Make sure to check if window is defined before using it.
*
*/
export const useWindow = (): Window | undefined => {
const [window, setWindow] = useState<Window | undefined>();
useEffect(() => {
setWindow(window);
}, []);
return window;
};
/**
* Generated by
* @link - https://chat.openai.com
*
* This is the same as the above, but it uses a ref instead of state.
*
* This removes the to add a window existence check in the component,
* but returns an runtime error if the window is not defined.
*/
const useWindowRef = (): Window => {
const windowRef = useRef<Window | null>(null);
useEffect(() => {
windowRef.current = window;
}, []);
return windowRef.current!;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment