Files
30-seconds-of-code/snippets/use-isomporphic-effect.md
Angelos Chalaris f1ce423d01 Kebab file names
2023-04-27 22:04:15 +03:00

32 lines
718 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.createRoot(document.getElementById('root')).render(
<MyApp />
);
```