Last active
March 16, 2023 21:30
-
-
Save yonigoldberg/b887508d6be70f8ce01637b5e690ad2d to your computer and use it in GitHub Desktop.
React component to disable children that are not suitable for SSR (Rehydration)
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
import { ReactNode, useState, useEffect } from 'react'; | |
type IsBrowserProps = { | |
children: ReactNode; | |
}; | |
export const IsBrowser = ({ children }: IsBrowserProps) => { | |
const [isBrowser, setIsBrowser] = useState(false); | |
// this useEffect does not run during SSR | |
useEffect(() => { | |
setIsBrowser(true); | |
}, []); | |
if (!isBrowser) { | |
// Justification: We specifically need to return an element instead of null | |
// in order to have stable content during SSR | |
// eslint-disable-next-line react/jsx-no-useless-fragment | |
return <></>; | |
} | |
// eslint-disable-next-line react/jsx-no-useless-fragment | |
return <>{children}</>; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment