usePrevious

After switching to hooks, I wondered how to get value from the last render. In class component's componentDidUpdate, we can access prevState and prevProps. In a hooks-based component, for this purpose we can utilize useRef hook and then access ref.current. This utility hook will be useful in any modern React codebase.

1
2
3
4
5
6
7
8
9
function usePrevious(value) {
  const ref = useRef()

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

  return ref.current
}