ClientOnly

A React component for rendering content only on the client side

If your React app has server-side rendering (SSR), you may want to render certain things only on the client.

For example, my website has code blocks with syntax highlighting. Syntax highlighting bloats the HTML with many elements for the different code tokens, increasing the server response size and time.

To avoid that, I render the source code without the syntax highlighting on the server, and then add the syntax highlighting on the client.

To do that, I created this hook & component:

js
export const useIsClient = () => {
    const [isClient, setIsClient] = useState(false);
    useEffect(() => {
        setIsClient(true);
    }, []);
    return isClient;
}

export const ClientOnly = ({server, children}) => {
    const isClient = useIsClient();
    return isClient ? children : server;
};

The children of this component will only be rendered on the client, and whatever you pass to server will be rendered on the server:

jsx
<ClientOnly server={/* will be rendered on the server */}>
    /* will be rendered on the client */
</ClientOnly>