react-usekit

Beta

useIsomorphicLayoutEffect

A custom hook that provides a cross-platform compatible useLayoutEffect.

Installation

npx react-usekit@latest init

Select: hooks → TypeScript or JavaScript → path -> useIsomorphicLayoutEffect

Usage

import { useIsomorphicLayoutEffect } from "./hooks/useIsomorphicLayoutEffect";
import { useState, useRef } from "react";

function App() {
  const [dimensions, setDimensions] = useState({ width: 0, height: 0 });
  const elementRef = useRef<HTMLDivElement>(null);

  useIsomorphicLayoutEffect(() => {
    if (elementRef.current) {
      const { offsetWidth, offsetHeight } = elementRef.current;
      setDimensions({ width: offsetWidth, height: offsetHeight });
    }
  }, []);

  return (
    <div>
      <div
        ref={elementRef}
        style={{ padding: "20px", border: "1px solid #ccc" }}
      >
        This element is being measured
      </div>
      <p>
        Dimensions: {dimensions.width} x {dimensions.height}
      </p>
    </div>
  );
}

API

Parameters

ParameterTypeDescription
effect() => void | (() => void)The effect function to run
depsReact.DependencyList | undefinedThe dependencies array for the effect

Returns

This hook doesn't return anything.