From 8c6f4675beac9c71e96126dd6f06f455c4e4bf01 Mon Sep 17 00:00:00 2001 From: xobotyi Date: Mon, 15 Jun 2020 14:37:37 +0300 Subject: [PATCH] feat(usePrevious): reworked the hook, now it is more memory-efficient. Better to use two-variables exchange than `useEffect` with new function on each render. --- src/usePrevious.ts | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/src/usePrevious.ts b/src/usePrevious.ts index 658f0f68e6..69592b75ad 100644 --- a/src/usePrevious.ts +++ b/src/usePrevious.ts @@ -1,13 +1,11 @@ -import { useEffect, useRef } from 'react'; +import { useRef } from 'react'; -const usePrevious = (state: T): T | undefined => { - const ref = useRef(); +export default function usePrevious(state: T): T | undefined { + const curRef = useRef(); + const prevRef = useRef(); - useEffect(() => { - ref.current = state; - }); + prevRef.current = curRef.current; + curRef.current = state; - return ref.current; -}; - -export default usePrevious; + return prevRef.current; +}