From fd286152038c6adc0ad35f062028a0cf029b4e71 Mon Sep 17 00:00:00 2001 From: 30secondsofcode <30secondsofcode@gmail.com> Date: Sat, 24 Aug 2019 10:19:19 +0000 Subject: [PATCH] Travis build: 18 --- README.md | 62 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/README.md b/README.md index fb94f54e3..58fb3148e 100644 --- a/README.md +++ b/README.md @@ -60,6 +60,7 @@ import ReactDOM from 'react-dom'; * [`useClickOutside`](#useclickoutside) * [`useFetch`](#usefetch) * [`useInterval`](#useinterval) +* [`useSSR`](#usessr) * [`useTimeout`](#usetimeout) @@ -460,6 +461,67 @@ ReactDOM.render(, document.getElementById('root'));
[⬆ Back to top](#contents) +### 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` and `window.document.createElement` to check if the code is running on the browser. +- Use the `React.useState()` hook to define the `inBrowser` state variable. +- Use the `React.useEffect()` hook to update the `inBrowser` state variable and clean up at the end. +- Use the `React.useMemo()` to memoize the return values of the custom hook. + +```jsx +const isDOMavailable = !!( + typeof window !== 'undefined' && + window.document && + window.document.createElement +); + +const useSSR = (callback, delay) => { + const [inBrowser, setInBrowser] = React.useState(isDOMavailable); + + React.useEffect(() => { + setInBrowser(isDOMavailable); + return () => { + setInBrowser(false); + } + }, []); + + const useSSRObject = React.useMemo(() => ({ + isBrowser: inBrowser, + isServer: !inBrowser, + canUseWorkers: typeof Worker !== 'undefined', + canUseEventListeners: inBrowser && !!window.addEventListener, + canUseViewport: inBrowser && !!window.screen + }), [inBrowser]); + + return React.useMemo(() => Object.assign(Object.values(useSSRObject), useSSRObject), [inBrowser]); +}; + +const SSRChecker = props => { + let { isBrowser, isServer } = useSSR(); + + return

{ isBrowser ? 'Running on browser' : 'Running on server' }

; +}; +``` + +
+Examples + +```jsx +const SSRChecker = props => { + let { isBrowser, isServer } = useSSR(); + + return

{ isBrowser ? 'Running on browser' : 'Running on server' }

; +}; + +ReactDOM.render(, document.getElementById('root')); +``` +
+ +
[⬆ Back to top](#contents) + ### useTimeout A hook that implements `setTimeout` in a declarative manner.