MENU
usePrevious
Accessing the previous value of a state is a relatively common use case. You can achieve this with a custom hook and a ref:
Click the button a few times to see 'before' always lag one render behind 'Now'.
RESETRUNFULL
RESETRUNFULL
<!DOCTYPE html><html><head>
<script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
</head><body>
<div></div>
<script type="text/babel">
const {useState, useRef, useEffect} = React;
function Counter() {
const [count, setCount] = useState(0);
const prevCount = usePrevious(count);
return (
<React.Fragment>
<button onClick={() => setCount(count + 1)}>Increment</button>
<h1>Now: {count}, before: {String(prevCount)}</h1>
</React.Fragment>
);}
function usePrevious(value) {
const ref = useRef();
useEffect(() => {
ref.current = value;
});
return ref.current;}
const root = ReactDOM.createRoot(document.querySelector("div"));
root.render(<Counter/>);
</script>
</body></html>This would work for props, state, or any other calculated value.