Skip to content

Instantly share code, notes, and snippets.

@wklsh
Last active June 3, 2020 11:03
Show Gist options
  • Save wklsh/2bc8f80c97ea691770de3317712b0c90 to your computer and use it in GitHub Desktop.
Save wklsh/2bc8f80c97ea691770de3317712b0c90 to your computer and use it in GitHub Desktop.
SSR / SR Rehydration Rendering
function function_component() {
const hasMounted = useHasMounted();
// has to be declared in function's body prior to usage
// has to be on top to nullify unmounted runs
if (!hasMounted) {
return null;
}
// ...code runs here
return (
<div>function_component</div>
);
};
// https://joshwcomeau.com/react/the-perils-of-rehydration/
import react, { useState, useEffect } from "react";
export default function useHasMounted() {
const [hasMounted, setHasMounted] = useState(false);
useEffect(() => {
setHasMounted(true);
}, []);
return hasMounted;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment