Get the previous value of a state or prop
Quick Answer
usePrevious stores the value from the last render in a ref. Because refs do not trigger re-renders and effects run after painting, ref.current always holds the previous render's value during the current render.
1import { useEffect, useRef } 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}usePrevious stores the value from the last render using a ref. Because updating a ref does not trigger a re-render, and the effect runs after the render, ref.current always holds the value from the previous render cycle when the component reads it during the current render.
Updating a ref does not trigger a re-render. If you used setState to store the previous value, every value change would cause two renders.
undefined, because the ref has not been set by the first useEffect yet.
This free typescript code snippet for useprevious hook is production-ready and copy-paste friendly. Whether you are building a web app, API, or frontend interface, this beginner-level example will help you implement useprevious hook quickly and correctly.
All snippets in the Snippetly library follow typescript best practices and are tested for real-world use. You can adapt this code to work with React, Vue, Node.js, or any project that uses typescript.
Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.