All files / src/utils use-force-update.ts

100% Statements 15/15
100% Branches 2/2
100% Functions 4/4
100% Lines 12/12

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 2532x 32x 32x   32x 260x 260x 260x   260x 18x             260x 19x       260x    
import sync from "framesync"
import { useState, useCallback, useRef } from "react"
import { useUnmountEffect } from "./use-unmount-effect"
 
export function useForceUpdate(): [VoidFunction, number] {
    const isUnmountingRef = useRef(false)
    const [forcedRenderCount, setForcedRenderCount] = useState(0)
    useUnmountEffect(() => (isUnmountingRef.current = true))
 
    const forceRender = useCallback(() => {
        !isUnmountingRef.current && setForcedRenderCount(forcedRenderCount + 1)
    }, [forcedRenderCount])
 
    /**
     * Defer this to the end of the next animation frame in case there are multiple
     * synchronous calls.
     */
    const deferredForceRender = useCallback(
        () => sync.postRender(forceRender),
        [forceRender]
    )
 
    return [deferredForceRender, forcedRenderCount]
}