🎣 Client-only React

👋 FYI, this note is over 6 months old. Some of the content may be out of date.
On this page

A client-only wrapper component Jump to heading

export const ClientOnly = ({ children, ...delegated }) => {
const [hasMounted, setHasMounted] = React.useState(false)
React.useEffect(() => {
setHasMounted(true)
}, [])
if (!hasMounted) {
return null
}
return <div {...delegated}>{children}</div>
}

Use like so:

<ClientOnly>
<Navigation />
</ClientOnly>

or you could use a hook:

export const useHasMounted = () => {
const [hasMounted, setHasMounted] = React.useState(false)
React.useEffect(() => {
setHasMounted(true)
}, [])
return hasMounted
}

Which could be used like so:

function Navigation() {
const hasMounted = useHasMounted()
if (!hasMounted) {
return null
}

const user = getUser()

if (user) {
return <AuthenticatedNav user={user} />
}

return (
<nav>
<a href="/login">Login</a>
</nav>
)
}

← Back home