useInsertionEffect — insert styles before layout effects.
1import { useInsertionEffect, useRef } from "react";23function useCSSAnimation(name, keyframes) {4 const styleRef = useRef();5 useInsertionEffect(() => {6 const style = document.createElement("style");7 style.textContent = `@keyframes ${name} { ${keyframes} }`;8 document.head.appendChild(style);9 styleRef.current = style;10 return () => { styleRef.current.remove(); };11 }, [name, keyframes]);12}
When to use: CSS-in-JS libraries, dynamic style injection, avoids FOUC.
Execution order: