Skip to content

Commit

Permalink
feat: Add usePrevious.
Browse files Browse the repository at this point in the history
  • Loading branch information
jaywcjlove committed Jul 31, 2021
1 parent 5955375 commit c283a85
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions components/utils/hooks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import {useRef, useEffect} from 'react';

/**
* 获取上一轮的 props 或 state
* How to get the previous props or state?
* https://reactjs.org/docs/hooks-faq.html#how-to-get-the-previous-props-or-state
* @example
* ```js
* function Counter() {
* const [count, setCount] = useState(0);
* const prevCount = usePrevious(count);
* return <h1>Now: {count}, before: {prevCount}</h1>;
* }
* ```
*/
export function usePrevious<T>(value: T) {
const ref = useRef<T>();
useEffect(() => {
ref.current = value;
});
return ref.current;
}

0 comments on commit c283a85

Please sign in to comment.