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
Width | Height | X Pos | Y Pos |
---|---|---|---|
0 px | 0 px | 0 px | 0 px |
Usage
Import the hook from @abhushanaj/react-hooks
and use in required component;
API Reference
Parameters
The signature for the useIsomorphicLayoutEffect
is exactly same to one provided by React.useEffect
and React.useLayoutEffect
.
Parameter | Type | Description | Default |
---|---|---|---|
callback | React.EffectCallback | The callback function to run when the dependencies change. | N/A |
dependencies | React.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:
This is a popular stratergy also used by other popular libraries like redux.