Skip to content

Instantly share code, notes, and snippets.

@amit08255
Created January 5, 2023 08:27
Show Gist options
  • Save amit08255/de985b817de7384aae3417f6c4174389 to your computer and use it in GitHub Desktop.
Save amit08255/de985b817de7384aae3417f6c4174389 to your computer and use it in GitHub Desktop.
Fix React Hydration Errors

Fix React Hydration Errors

Remove content from initial render (WORKS BEST)

export default function NoFirstRender({ theDate }) {
	const [hydrated, setHydrated] = React.useState(false);
	React.useEffect(() => {
		// This forces a rerender, so the date is rendered
		// the second time but not the first
		setHydrated(true);
	}, []);
	if (!hydrated) {
		// Returns null on first render, so the client and server match
		return null;
	}

	const formatted_date = new Date(theDate).toLocaleDateString();
	return <div>{formatted_date}</div>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment