Skip to content

Commit 7a94200

Browse files
committed
react: Add usePrevious.
1 parent 8287500 commit 7a94200

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

src/utils/react.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
/* @flow strict-local */
2+
import { useRef, useEffect } from 'react';
3+
4+
/**
5+
* A Hook for the value of a prop, state, etc., from the previous
6+
* render, or the first render if this is the first.
7+
*
8+
* From
9+
* https://reactjs.org/docs/hooks-faq.html#how-to-get-the-previous-props-or-state,
10+
* which says, "It’s possible that in the future React will provide a
11+
* `usePrevious` Hook out of the box since it’s a relatively common
12+
* use case."
13+
*/
14+
export function usePrevious<T>(value: T): T {
15+
const ref = useRef<T>(value);
16+
useEffect(() => {
17+
ref.current = value;
18+
});
19+
return ref.current;
20+
}

0 commit comments

Comments
 (0)