usePrevious
Get the previous state or prop based on the value from previous render.
tip
If you want the previous value based on equality, then use usePreviousDistinct
API​
const prevState = usePrevious(state);
Options​
state: any (T)
(Required)- The state (or prop) value
Returns​
prevState: T (generic)
- The previous value of the state (or prop) from the previous render
Examples​
http://localhost:3000/
Count: 0
Previous count: undefined
- JS
- TS
import { useState } from 'react';
import { usePrevious } from 'react-power-ups';
export function Demo() {
const [count, setCount] = useState(0);
const increment = () => setCount((prev) => prev + 1);
const prevCount = usePrevious(count);
const [, triggerReRender] = useState(0);
return (
<>
<div>Count: {count}</div>
<button onClick={increment}>Increment</button>
<div>Previous count: {prevCount ?? <i>undefined</i>}</div>
<button onClick={() => triggerReRender(Math.random())}>Trigger Re-Render</button>
</>
);
}
import { useState } from 'react';
import { usePrevious } from 'react-power-ups';
export function Demo() {
const [count, setCount] = useState(0);
const increment = () => setCount((prev) => prev + 1);
const prevCount = usePrevious(count);
const [, triggerReRender] = useState(0);
return (
<>
<div>Count: {count}</div>
<button onClick={increment}>Increment</button>
<div>Previous count: {prevCount ?? <i>undefined</i>}</div>
<button onClick={() => triggerReRender(Math.random())}>Trigger Re-Render</button>
</>
);
}
Code: https://github.com/afiiif/react-power-ups/blob/main/src/use-previous.ts