Avoid weird SSR issues with this handy React hook. Know whether you're rendering on the client or server!
JSXimport { useState, useEffect } from 'react'; function useHasMounted() { const [hasMounted, setHasMounted] = useState(false); useEffect(() => { setHasMounted(true); }, []); return hasMounted; }
Last Updated:JSXconst SomeClientSideOnlyComponent = () => { const hasMounted = useHasMounted(); if (!hasMounted) { return null; } return <div>Client only!</div>; };