JavaScript Snippet

React usePrevious Hook

Difficulty: Easy

Tracking the previous value of a prop or piece of state lets you diff renders, animate transitions, and detect specific change patterns. This snippet shows the canonical one-liner usePrevious, a useChanged variant that returns whether the value just changed, and a useHistory hook that keeps the last N values for undo / redo. All three are tiny but easy to get subtly wrong.

Code Snippets
/

React usePrevious Hook

React usePrevious Hook

Tracking the previous value of a prop or piece of state lets you diff renders, animate transitions, and detect specific change patterns. This snippet shows the canonical one-liner usePrevious, a useChanged variant that returns whether the value just changed, and a useHistory hook that keeps the last N values for undo / redo. All three are tiny but easy to get subtly wrong.

JavaScript
Easy
3 snippets
react
hooks
code-template
references

203 views

6

The hook stores the value in a ref and updates it inside useEffect, which runs AFTER the render commits. That ordering is the whole trick: during render, ref.current still holds the value from the previous commit, so the component sees the prior value while React holds the new one. On the very first render the ref is undefined, which usually models the initial state correctly. This is the textbook implementation and the one most React projects copy-paste.