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 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'));

Written by Angelos Chalaris

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub or Twitter.

More like this