Created
September 14, 2021 16:14
-
-
Save JBaczuk/410cd7b9da177acfe22721ef5735ec5b to your computer and use it in GitHub Desktop.
usePrevious - How to get the previous props or state in React
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useEffect, useRef, useState } from "react"; | |
function usePrevious(value: number) { | |
const ref = useRef<number | null>(null); | |
useEffect(() => { | |
ref.current = value; | |
}); | |
return ref.current; | |
} | |
export default function Counter() { | |
const [count, setCount] = useState(0); | |
const prev = usePrevious(count); | |
return ( | |
<div> | |
<p>Current: {count}</p> | |
<p>Previous: {prev}</p> | |
<button onClick={() => setCount(count + 1)}>Increment</button> | |
<button onClick={() => setCount(count - 1)}>Decrement</button> | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment