Skip to content

Instantly share code, notes, and snippets.

@sky0014
Last active May 8, 2024 12:37
Show Gist options
  • Save sky0014/78b459f5c99ff24af9570b92cd72fa84 to your computer and use it in GitHub Desktop.
Save sky0014/78b459f5c99ff24af9570b92cd72fa84 to your computer and use it in GitHub Desktop.
NoSSR lazy loader
import React, { PropsWithChildren, useEffect, useState } from 'react';
export default function NoSSRLoad<T extends React.ComponentType<PropsWithChildren<any>>>(loader: () => Promise<{ default: T }>) {
const NoSSRLoadWrap = (props) => {
const [Component, setComponent] = useState<T>();
useEffect(() => {
// Don't use: loader().then((m) => setComponent(m.default));
// When m.default is function, set state of a function will be treated as an updater function, just like setAge(age => age+1);
// That's not what you want.
loader().then((m) => setComponent(() => m.default));
}, []);
if (!Component) {
return props.children || null;
}
return React.createElement(Component, props);
};
return NoSSRLoadWrap as T;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment