Skip to content

Instantly share code, notes, and snippets.

@yonigoldberg
Last active March 16, 2023 21:30
Show Gist options
  • Save yonigoldberg/b887508d6be70f8ce01637b5e690ad2d to your computer and use it in GitHub Desktop.
Save yonigoldberg/b887508d6be70f8ce01637b5e690ad2d to your computer and use it in GitHub Desktop.
React component to disable children that are not suitable for SSR (Rehydration)
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