Back to library
⚛️Reacttypescriptbeginner

usePrevious Hook

React hook to get previous value of state or props

hooksstate-management

Code

1import { useRef, useEffect } from 'react';
2
3function usePrevious<T>(value: T): T | undefined {
4  const ref = useRef<T>();
5  
6  useEffect(() => {
7    ref.current = value;
8  }, [value]);
9  
10  return ref.current;
11}
12
13// Usage example
14function Counter() {
15  const [count, setCount] = useState(0);
16  const prevCount = usePrevious(count);
17
18  return (
19    <div>
20      <p>Current: {count}</p>
21      <p>Previous: {prevCount}</p>
22      <button onClick={() => setCount(count + 1)}>
23        Increment
24      </button>
25    </div>
26  );
27}

Quick Tips

  • Click the "Copy" button to copy the code to your clipboard
  • This code is production-ready and can be used in your projects
  • Check out related snippets below for more examples

Related Snippets

Build Your Own Snippet Library

Organize your team's code snippets with Snippetly. Share knowledge and boost productivity across your organization.