From b684de5ce1bee600724ee97fedd7d037368651af Mon Sep 17 00:00:00 2001 From: Rick Huizing Date: Mon, 23 Dec 2024 12:19:56 +0100 Subject: [PATCH] fix: remove unnecessary useEffect and ref in usePrevious hook --- docs/usePrevious.md | 2 +- src/usePrevious.ts | 14 ++++++++------ 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/docs/usePrevious.md b/docs/usePrevious.md index 76c49d4abd..ef8935ab06 100644 --- a/docs/usePrevious.md +++ b/docs/usePrevious.md @@ -1,6 +1,6 @@ # `usePrevious` -React state hook that returns the previous state as described in the [React hooks FAQ](https://reactjs.org/docs/hooks-faq.html#how-to-get-the-previous-props-or-state). +React state hook that returns the previous state as described in [Adjusting some state when a prop changes](https://react.dev/learn/you-might-not-need-an-effect#adjusting-some-state-when-a-prop-changes). ## Usage diff --git a/src/usePrevious.ts b/src/usePrevious.ts index a5233144ca..ff745537b8 100644 --- a/src/usePrevious.ts +++ b/src/usePrevious.ts @@ -1,11 +1,13 @@ -import { useEffect, useRef } from 'react'; +import { useState } from 'react'; export default function usePrevious(state: T): T | undefined { - const ref = useRef(); + const [current, setCurrent] = useState(state); + const [previous, setPrevious] = useState(); - useEffect(() => { - ref.current = state; - }); + if (current !== state) { + setCurrent(state); + setPrevious(current); + } - return ref.current; + return previous; }