Files
30-seconds-of-code/snippets/useIsomporphicEffect.md
Angelos Chalaris f39deb9522 Update to React 18
2023-04-14 20:32:31 +03:00

718 B

title, tags, author, cover, firstSeen, lastUpdated
title tags author cover firstSeen lastUpdated
React useIsomporphicEffect hook hooks,effect chalarangelo jars-on-shelf-2 2021-09-29T05:00:00-04:00 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 />
);