React useIsomporphicEffect hook
React, Hooks, Effect · Oct 13, 2021

Resolves to useEffect()
on the server and useLayoutEffect()
on the client.
- Use
typeof
to check if theWindow
object is defined. If it is, return theuseLayoutEffect()
. Otherwise returnuseEffect()
.
const useIsomorphicEffect =
typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect;
const MyApp = () => {
useIsomorphicEffect(() => {
window.console.log('Hello');
}, []);
return null;
};
ReactDOM.render(<MyApp />, document.getElementById('root'));