Update hook descriptions

This commit is contained in:
Isabelle Viktoria Maciohsek
2020-11-16 14:17:53 +02:00
parent 9e9e7443c2
commit eeccde742b
13 changed files with 121 additions and 96 deletions

View File

@ -3,13 +3,13 @@ title: useSSR
tags: hooks,effect,state,memo,intermediate
---
A hook that checks if the code is running on the browser or the server.
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.
- Use `typeof window`, `window.document` and `Document.createElement()` to check if the code is running on the browser.
- Use the `useState()` hook to define the `inBrowser` state variable.
- Use the `useEffect()` hook to update the `inBrowser` state variable and clean up at the end.
- Use the `useMemo()` hook to memoize the return values of the custom hook.
```jsx
const isDOMavailable = !!(
@ -25,18 +25,24 @@ const useSSR = (callback, delay) => {
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]);
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]);
return React.useMemo(
() => Object.assign(Object.values(useSSRObject), useSSRObject),
[inBrowser]
);
};
```
@ -44,7 +50,7 @@ const useSSR = (callback, delay) => {
const SSRChecker = props => {
let { isBrowser, isServer } = useSSR();
return <p>{ isBrowser ? 'Running on browser' : 'Running on server' }</p>;
return <p>{isBrowser ? 'Running on browser' : 'Running on server'}</p>;
};
ReactDOM.render(<SSRChecker />, document.getElementById('root'));