Files
30-seconds-of-code/snippets/useIsomporphicEffect.md
Angelos Chalaris df6770fc51 Update covers
2023-02-16 22:24:44 +02:00

30 lines
703 B
Markdown

---
title: React useIsomporphicEffect hook
tags: hooks,effect
author: chalarangelo
cover: jars-on-shelf-2
firstSeen: 2021-09-29T05:00:00-04:00
lastUpdated: 2021-10-13T19:29:39+02:00
---
Resolves to `useEffect()` on the server and `useLayoutEffect()` on the client.
- Use `typeof` to check if the `Window` object is defined. If it is, return the `useLayoutEffect()`. Otherwise return `useEffect()`.
```jsx
const useIsomorphicEffect =
typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect;
```
```jsx
const MyApp = () => {
useIsomorphicEffect(() => {
window.console.log('Hello');
}, []);
return null;
};
ReactDOM.render(<MyApp />, document.getElementById('root'));
```