aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/examples/with-changesets/packages/acme-utils/src/usePrevious.tsx
blob: 8024464562fddcdc0d0699ee7593d16314cee16a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import * as React from "react";

function usePrevious<T>(value: T) {
  // 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 = React.useRef<T>(value);

  // Store current value in ref
  React.useEffect(() => {
    ref.current = value;
  }, [value]); // Only re-run if value changes

  // Return previous value (happens before update in useEffect above)
  return ref.current;
}

export { usePrevious };