Skip to content

Instantly share code, notes, and snippets.

@iRoachie
Created February 6, 2023 15:32
Show Gist options
  • Save iRoachie/8c8d1e41c3efa213540d6953b23b42b6 to your computer and use it in GitHub Desktop.
Save iRoachie/8c8d1e41c3efa213540d6953b23b42b6 to your computer and use it in GitHub Desktop.
Simple component to show dates without server/client mismatch
import { format } from 'date-fns';
const App = () => {
return <RenderDate>{format(new Date(utcDate), 'MMMM d, yyyy')}</RenderDate>
}
import classNames from 'classnames';
import { useEffect, useState } from 'react';
interface Props {
children: React.ReactNode;
}
export const RenderDate = ({ children }: Props) => {
const [hasMounted, setHasMounted] = useState(false);
useEffect(() => {
setHasMounted(true);
}, []);
const classes = classNames({
'transition-opacity duration-300 ease-in-out': true,
'opacity-0': !hasMounted,
'opacity-100': hasMounted,
});
return (
<time suppressHydrationWarning className={classes}>
{children}
</time>
);
};
@iRoachie
Copy link
Author

iRoachie commented Feb 6, 2023

Even though this is a two-pass render, we still use suppressHydrationWarning cause we still need to maintain the layout.

If we were to return null on the server like this article we'd get a layout shift when the hydration is complete.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment