30秒学会 React 片段 – useSSR
A hook that checks if the code is running on the browser or the server.
- Create a custom hook that returns an appropriate object.
- Use
typeof window
,window.document
andwindow.document.createElement
to check if the code is running on the browser. - Use the
React.useState()
hook to define theinBrowser
state variable. - Use the
React.useEffect()
hook to update theinBrowser
state variable and clean up at the end. - Use the
React.useMemo()
to memoize the return values of the custom hook.