Page cover image

Client-only Component

A work-around to using components that cannot be rendered on server-side
  • Front-end
  • React
Created
May 4, 2021 02:28 PM
Description
A work-around to using components that cannot be rendered on server-side
Last Edited
Sep 8, 2022 04:03 PM
Tags
Front-end
React

Client-Only Wrapper Component

Children of this component is only rendered on the client-side after the initial render. This is useful for preventing rehydration errors caused by components that rely on states that are only available on the client-side (e.g. locale, time, sensor).
function ClientOnly({ children }) { const [hasMounted, setHasMounted] = React.useState(false) React.useEffect(() => { setHasMounted(true) }, []); if (!hasMounted) { return null } return children; }

Usage

<ClientOnly> <Navigation /> </ClientOnly>

Use Has Mounted Hook

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

Usage

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

Source