⚛ Conditionally render on the client or server

👋 FYI, this note is over 6 months old. Some of the content may be out of date.
On this page
import React, { useEffect, useState, ReactNode } from 'react'

export interface ConditionallyRenderProps {
client?: boolean
server?: boolean
children?: ReactNode
}

const ConditionallyRender = ({
client,
server,
children,
}: ConditionallyRenderProps) => {
const [isMounted, setIsMounted] = useState(false)

useEffect(() => setIsMounted(true), [])

if (!isMounted && client) {
return null
}

if (isMounted && server) {
return null
}

return children as React.ReactElement
}

export default ConditionallyRender

Usage Jump to heading

<Layout>
<ConditionallyRender server>
<p>This is rendered only on server.</p>
</ConditionallyRender>
<ConditionallyRender client>
<p>This is rendered only on client.</p>
</ConditionallyRender>
</Layout>

← Back home