React useprevious() hook

Hooks are essential for the functional component pattern in React. One frequent logic comparison with class components was comparing a previous prop value with a current prop value via lifecycle methods. So what's an easy pattern for duplicating previous value comparisons in functional components?

The useRef and useEffect hooks allow us manage that same functionality in functional components via a custom hook -- usePrevious:

import { useEffect, useRef } from 'react';

export function usePrevious(value) {
const ref = useRef();
useEffect(() => {
ref.current = value;
}, [value]);
return ref.current;
}

// Usage
export function MyComponent(props) {
const { name } = props;
const previousName = usePrevious(name);

if(name != previousName) {
// Do something
}
}

I love this usePrevious hook, if only because I frequently forget to use the .current property and it helps avoid some boilerplate code.

--

--