All files / hooks/use-isomorphic-layout-effect/src useIsomorphicLayoutEffect.ts

100% Statements 1/1
50% Branches 1/2
100% Functions 0/0
100% Lines 1/1

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24                                            1x  
import { useEffect, useLayoutEffect } from "react";
 
/**
 * An SSR-safe version of `useLayoutEffect`.
 *
 * `useLayoutEffect` warns when it runs on the server (it can't do anything
 * useful there). This hook resolves to `useLayoutEffect` in the browser and to
 * `useEffect` on the server, silencing the warning while keeping synchronous
 * layout behavior on the client.
 *
 * The choice is made once at module load based on whether `window` exists, so
 * it is stable for the lifetime of the app.
 *
 * @example
 * ```tsx
 * useIsomorphicLayoutEffect(() => {
 *   const rect = ref.current?.getBoundingClientRect();
 *   setSize(rect);
 * }, []);
 * ```
 */
export const useIsomorphicLayoutEffect =
  typeof window !== "undefined" ? useLayoutEffect : useEffect;