How to get the previous props or state in React?

Picture of Jordan Baczuk
By Jordan Baczuk

In React class components, we had the componentDidUpdate method, which provided the previous prop and state arguments. Now, with functional components, we have effects. In order to accomplish saving the previous state and prop values, we can store them to a ref. Refs do not have to be a DOM object.

1import React, { useEffect, useRef, useState } from "react"; 2 3function usePrevious(value: number) { 4 const ref = useRef<number | null>(null); 5 useEffect(() => { 6 ref.current = value; 7 }); 8 return ref.current; 9} 10 11export default function Counter() { 12 const [count, setCount] = useState(0); 13 14 const prev = usePrevious(count); 15 16 return ( 17 <div> 18 <p>Current: {count}</p> 19 <p>Previous: {prev}</p> 20 <button onClick={() => setCount(count + 1)}>Increment</button> 21 <button onClick={() => setCount(count - 1)}>Decrement</button> 22 </div> 23 ); 24}

usePrevious stores the value to the ref, but the useEffect doesn’t run until the component is rendered. So the current value is returned, and it is stored for next time. Then, in the component, you can use usePrevious and pass it the value you want to keep track of.