Created
November 11, 2021 15:31
-
-
Save peplocanto/f24bfc76442202602f65358474143839 to your computer and use it in GitHub Desktop.
isSsr_hook.ts
This file contains 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
// best practice arch | |
// app | |
// L hooks | |
// L useIsSsr.hook.ts | |
// useIsSsr.hook.ts | |
import { useState, useEffect } from "react"; | |
const useIsSsr = () => { | |
const [isSsr, setIsSsr] = useState(true); | |
useEffect(() => { | |
setIsSsr(false); | |
}, []); | |
return isSsr; | |
} | |
// my-component.component.ts | |
const MyComponent = () => { | |
const isSsr = useIsSsr(); | |
const screenWidth = isSsr ? null : window.innerWidth; | |
const width = screenWidth | |
? screenWidth | |
: '...'; | |
return ( | |
<div> | |
<p>{Your Width Is:}</p> | |
<p>{width}</p> | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment