Files
30-seconds-of-code/snippets/useIsomporphicEffect.md
Isabelle Viktoria Maciohsek 790f0de37f Update formatting
2022-01-30 19:40:51 +02:00

657 B

title, tags, firstSeen, lastUpdated
title tags firstSeen lastUpdated
useIsomporphicEffect hooks,effect,beginner 2021-09-29T05:00:00-04:00 2021-10-13T19:29:39+02:00

Eesolves 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().
const useIsomorphicEffect =
  typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect;
const MyApp = () => {
  useIsomorphicEffect(() => {
    window.console.log('Hello');
  }, []);

  return null;
};

ReactDOM.render(<MyApp />, document.getElementById('root'));