Skip to content

Instantly share code, notes, and snippets.

@kylelambert101
Created September 22, 2021 18:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kylelambert101/42af431e6d7b4f3c10cf33b97b6d7390 to your computer and use it in GitHub Desktop.
Save kylelambert101/42af431e6d7b4f3c10cf33b97b6d7390 to your computer and use it in GitHub Desktop.
React -> Use Previous State Values
// From https://reactjs.org/docs/hooks-faq.html#how-to-get-the-previous-props-or-state
function Counter() {
const [count, setCount] = useState(0);
const prevCountRef = useRef();
useEffect(() => {
prevCountRef.current = count;
});
const prevCount = prevCountRef.current;
return <h1>Now: {count}, before: {prevCount}</h1>;
}
// Alternatively, extract to a custom hook:
function Counter() {
const [count, setCount] = useState(0);
const prevCount = usePrevious(count);
return <h1>Now: {count}, before: {prevCount}</h1>;
}
function usePrevious(value) {
const ref = useRef();
useEffect(() => {
ref.current = value;
});
return ref.current;
}
@kylelambert101
Copy link
Author

This is kind of unnecessary now since there's a usePrevious hook in @fluentui/react-hooks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment