Asked By: Anonymous
I have a project using React & NextJS. Currently, I have a custom _app.js that make the page become SSR. But now I want the page not being load on the server-side. Is there any way to do that?
Solution
Answered By: Anonymous
We can use next.js dynamic import (https://nextjs.org/docs/advanced-features/dynamic-import):
import dynamic from 'next/dynamic'
const DynamicComponentWithNoSSR = dynamic(() => import('../components/hello3'), { ssr: false })
You can also write HOC like:
import React from 'react';
const isClient = () => typeof window !== 'undefined';
export const withClientRenderOnly = <P extends Record<string, unknown>>(
WrappedComponent: React.ComponentType<P>
) => {
const WrappedWithClientRenderOnly: React.FC<P> = props => {
if (!isClient()) return null;
return <WrappedComponent {...props} />;
};
return WrappedWithClientRenderOnly;
};
Or create simple composition:
const ClientRenderOnly: React.FC = ({ children }) => {
const [isMounted, setMounted] = useState(false);
useEffect(() => setMounted(true), []);
if(!isMounted) return null;
return children;
};
const Page = () => <ClientRenderOnly>Page</ClientRenderOnly>