useValidElement()

description

  • When passing a reference to a parent component's Element to a child component, it cannot be referenced by the child component's `useLayoutEffect` due to the rendering order. The `useGSAP` uses `useLayoutEffect` and therefore gets the reference with `useValidElement`.

demo

console...

code

const Child = ({ trigger }: { trigger: React.RefObject<HTMLDivElement> }) => {
   useLayoutEffect(() => {
      if (!trigger.current) return;
      console.log(trigger.current, "child useLayoutEffect"); // undefined
   }, [trigger]);

   useEffect(() => {
      if (!trigger.current) return;
      console.log(trigger.current, "child useEffect"); // valid
   }, [trigger]);

   const validElement = useValidElement(trigger);
   useLayoutEffect(() => {
      if (!validElement) return;
      console.log(validElement, "child useLayoutEffect useValid"); // valid
   }, [validElement]);

   useEffect(() => {
      if (!validElement) return;
      console.log(validElement, "child useEffect useValid"); // valid
   }, [validElement]);

   return <div></div>;
};