Last active
December 22, 2022 22:31
-
-
Save luisvinicius09/78dfb5cafb77b3e10afffe03a0d9ee1e to your computer and use it in GitHub Desktop.
useWindow react hook
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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