--- title: Suspense breaks styles date: 2023-07-07 author: zombieJ --- We know that React 18 provides a `useInsertionEffect` hooks specifically for CSS-IN-JS, which has a faster timing priority than `useLayoutEffect`, so that the order of calls will not be affected by the order of writing: ```tsx useLayoutEffect(() => { console.log('layout effect'); }, []); useInsertionEffect(() => { console.log('insertion effect'); }, []); // Console: // - insertion effect // - layout effect ``` In early `@ant-design/cssinjs` implementation, we did not choose `useInsertionEffect` because we needed to be compatible with React 17 version, but simulated the effect of inserting in advance by adding styles in the render phase: ```tsx // pseudocode. Not used in real world function useStyleInsertion(hash: string, counter: Record) { useMemo(() => { if (!counter[hash]) { // Insert only when current style not inserted } counter[hash] += 1; }, [hash]); useEffect( () => () => { counter[hash] -= 1; if (!counter[hash]) { // Remove if set to clear on destroy } }, [hash], ); } ``` Above code will count the usage of styles, if the current style has not been inserted, it will insert the style in the render phase. Similarly, if the current style is configured to be unloaded when it is not in use, it will be cleared after the effect confirms the count. In addition, there is a similar logic that listens for changes in tokens, and when there are multiple tokens, it will clear all styles `