usePrevious() hook

usePrevious() hook will take the current value as input and hold it and will return it whenever it will get a new value. For the initial render, it will return undefined as there will not be any previous value for it.

Count: 0
Previous Count:

If we use State inside usePrevious, State updates happen and it causes re-render. So we wont get previous value. We end up getting latest value. To fix this we can use useRef. Ref can store value but it doesnot trigger a re-render.

const usePrevious = (value) => {
  const prevRef = useRef();

  useEffect(() => {
    prevRef.current = value;
  }, [value]);

  return prevRef.current;
};

const [count, setCount] = useState(0);
const previousCount = usePrevious(count);