Files
30-seconds-of-code/snippets/react/s/use-isomporphic-effect.md
2023-05-07 16:07:29 +03:00

714 B

title, type, language, tags, author, cover, dateModified
title type language tags author cover dateModified
React useIsomporphicEffect hook snippet react
hooks
effect
chalarangelo jars-on-shelf-2 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().
const useIsomorphicEffect =
  typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect;
const MyApp = () => {
  useIsomorphicEffect(() => {
    window.console.log('Hello');
  }, []);

  return null;
};

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