Skip to content

useIsomorphicLayoutEffect

Hook that resolves to useEffect on the server and useLayoutEffect on the client

The useIsomorphicLayoutEffect hook is helpful when you want to have an isomorphic version of an effect which resolves to React.useEffect on SRR and React.useLayoutEffect on browswers.

This is required as React currently throws a warning when using useLayoutEffect on the server. To get around it, we can conditionally useEffect on the server (no-op) and useLayoutEffect in the browser.

Usage

useIsomorphicLayoutEffect

Box
WidthHeightX PosY Pos
0 px0 px0 px0 px
Bounding box for the box element.

Usage

Import the hook from @abhushanaj/react-hooks and use in required component;

./src/App.tsx
import { useIsomorphicLayoutEffect } from '@abhushanaj/react-hooks';
function App() {
useIsomorphicLayoutEffect(() => {
console.log('Rendered');
}, []);
return (
<div>
<p>I am now rendered!</p>
</div>
);
}
export default App;

API Reference

Parameters

The signature for the useIsomorphicLayoutEffect is exactly same to one provided by React.useEffect and React.useLayoutEffect.

ParameterTypeDescriptionDefault
callbackReact.EffectCallbackThe callback function to run when the dependencies change.N/A
dependenciesReact.DependencyList | undefined (optional)An array of dependencies for the effect.undefined

Return Value

The hook returns React.useEffect when window is not defined (or likely undefined) and React.useLayoutEffect on the client where window is defined.

As based on different environment (some of them polyfilling window), the results returned can likely provide a false positive, we use the following condition to hopefully determine the environment is window:

// Hopefully the environemnt is window now.
export const isWindow = () =>
typeof window !== 'undefined' &&
typeof window.document !== 'undefined' &&
typeof window.document.createElement !== 'undefined';

This is a popular stratergy also used by other popular libraries like redux.