Skip to content

Commit

Permalink
Merge pull request #1295 from streamich/improve-usePrevious
Browse files Browse the repository at this point in the history
feat(usePrevious): reworked the hook, now it is more memory-efficient.
  • Loading branch information
xobotyi authored Jun 19, 2020
2 parents ee683ca + 8c6f467 commit f364b32
Showing 1 changed file with 8 additions and 10 deletions.
18 changes: 8 additions & 10 deletions src/usePrevious.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
import { useEffect, useRef } from 'react';
import { useRef } from 'react';

const usePrevious = <T>(state: T): T | undefined => {
const ref = useRef<T>();
export default function usePrevious<T>(state: T): T | undefined {
const curRef = useRef<T>();
const prevRef = useRef<T>();

useEffect(() => {
ref.current = state;
});
prevRef.current = curRef.current;
curRef.current = state;

return ref.current;
};

export default usePrevious;
return prevRef.current;
}

0 comments on commit f364b32

Please sign in to comment.