1 | import { useEffect, useRef } from 'react';
|
2 |
|
3 | /**
|
4 | * Store the last of some value. Tracked via a `Ref` only updating it
|
5 | * after the component renders.
|
6 | *
|
7 | * Helpful if you need to compare a prop value to it's previous value during render.
|
8 | *
|
9 | * ```ts
|
10 | * function Component(props) {
|
11 | * const lastProps = usePrevious(props)
|
12 | *
|
13 | * if (lastProps.foo !== props.foo)
|
14 | * resetValueFromProps(props.foo)
|
15 | * }
|
16 | * ```
|
17 | *
|
18 | * @param value the value to track
|
19 | */
|
20 | export default function usePrevious(value) {
|
21 | const ref = useRef(null);
|
22 | useEffect(() => {
|
23 | ref.current = value;
|
24 | });
|
25 | return ref.current;
|
26 | } |
\ | No newline at end of file |