Skip to content

Instantly share code, notes, and snippets.

@JBaczuk
Created September 14, 2021 16:14
Show Gist options
  • Save JBaczuk/410cd7b9da177acfe22721ef5735ec5b to your computer and use it in GitHub Desktop.
Save JBaczuk/410cd7b9da177acfe22721ef5735ec5b to your computer and use it in GitHub Desktop.
usePrevious - How to get the previous props or state in React
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