In React, you don’t have access to the previous render’s value. This is usually fine, but once in a while I find myself needing to access the previous values of a state for diverse reasons (e.g. recording analytics event on certain behaviours).
In that case, I use a custom hook called usePreviousValue
:
import { useEffect, useRef } from 'react'
export default function usePreviousValue(value) {
const ref = useRef()
useEffect(() => {
ref.current = value
})
return ref.current
}
It can be used this way:
const previousCount = usePreviousValue(count)
useEffect(() => {
if (previousCount && previousCount > count) {
analytics.trackEvent('count-decreased')
}
}, [previousCount, count])