All files usePrevious.js

100% Statements 4/4
100% Branches 0/0
100% Functions 2/2
100% Lines 4/4
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28                                  2x     2x 1x       2x    
import { useEffect, useRef } from "react"
 
/**
 * usePrevious Hook
 *
 * Got from https://usehooks.com/usePrevious/
 * It saves the previous value of props or state
 *
 * @param {*} value - The value to save
 *
 * @example
 * const [state, setState] = React.useState()
 * const prev = usePrevious(state)
 */
export function usePrevious(value) {
    // The ref object is a generic container whose current property is mutable ...
    // ... and can hold any value, similar to an instance property on a class
    const ref = useRef()
 
    // Store current value in ref
    useEffect(() => {
        ref.current = value
    }, [value]) // Only re-run if value changes
 
    // Return previous value (happens before update in useEffect above)
    return ref.current
}