UNPKG

@trellixio/roaster-coffee

Version:
42 lines (41 loc) 1.2 kB
import * as React from 'react'; /** * A custom React hook that invokes a specified effect function on every update after the initial render. * This hook is designed to avoid executing the effect on the first render, while still allowing it to execute on subsequent updates. * * @param fn - The effect function to be invoked on update after the initial render. * @param dependencies - The dependencies to be used by the `useEffect` hook that triggers the effect function. * * @example * ```tsx * import { useState } * function MyComponent() { * const [count, setCount] = useState(0); * * useDidUpdate(() => { * console.log('Component updated!'); * }, [count]); * * return ( * <div> * <p>Count: {count}</p> * <button onClick={() => setCount(count + 1)}>Increment</button> * </div> * ); * } * ``` * */ export function useDidUpdate(fn, dependencies) { const mounted = React.useRef(false); React.useEffect(() => () => { mounted.current = false; }, []); React.useEffect(() => { if (mounted.current) { return fn(); } mounted.current = true; return undefined; }, dependencies); }