Created
September 22, 2021 18:13
-
-
Save kylelambert101/42af431e6d7b4f3c10cf33b97b6d7390 to your computer and use it in GitHub Desktop.
React -> Use Previous State Values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is kind of unnecessary now since there's a
usePrevious
hook in @fluentui/react-hooks