Last active
May 8, 2024 12:37
-
-
Save sky0014/78b459f5c99ff24af9570b92cd72fa84 to your computer and use it in GitHub Desktop.
NoSSR lazy loader
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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