useHasMounted
const useHasMounted = () => {
const [hasMounted, setHasMounted] = React.useState(false);
React.useEffect(() => {
setHasMounted(true);
}, []);
return hasMounted;
}
Why?
When dealing with a server-side rendered application (through frameworks like Nextjs or Gatsby, or any sort of SSR setup), it can be useful to know whether you're rendering on the server or the client.
For example: If you don't have a dynamic backend (eg. a Nextjs app), you won't know whether the user is authenticated or not.
In that first pre-render, you should render a blank spot. When the client renders, you can fill it in, either with the user's avatar or a "Sign in" link.
Usage
const SomeClientSideOnlyComponent = () => {
const hasMounted = useHasMounted();
if (!hasMounted) {
return null;
}
return <div>Client only!</div>
};