Client-only Component content
Created
Description
A work-around to using components that cannot be rendered on server-side
Last Edited
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
}
