HooksState Management
usePreviousImmediate
Returns the previous value of a variable immediately after it changes.
About
usePreviousImmediate returns the value from the previous committed render, whether it is equal to the current value or not.
Examples
import { usePreviousImmediate, useCounter } from "rooks";
function App() {
const { value: counter1Value, increment: incrementCounter1 } = useCounter(0);
const previousCounter1Value = usePreviousImmediate(counter1Value);
const { value: counter2Value, increment: incrementCounter2 } = useCounter(0);
const previousCounter2Value = usePreviousImmediate(counter2Value);
return (
<div
style={{ display: "flex", flexDirection: "column", alignItems: "center" }}
>
<h2>Previous render values</h2>
<p>
This simply gives the value of a state variable in the previous render.
</p>
<div>
<p>Counter: {String(counter1Value)}</p>
<p>Previous Counter 1 value: {String(previousCounter1Value)}</p>
<p>Counter: {String(counter2Value)}</p>
<p>Previous Counter 1 value: {String(previousCounter2Value)}</p>
<button onClick={incrementCounter1}>Increment counter 1</button>
<br />
<button onClick={incrementCounter2}>Increment counter 2</button>
</div>
</div>
);
}
export default App;Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
currentValue | T | Required | Value whose history is tracked. |
Return value
Returns T | null. The first render returns null; later renders receive the value from the preceding committed render.
Behavior and lifecycle
An effect without a dependency list writes the current value after every commit. The render in progress therefore sees the value from the previous commit. Object values retain their original references, and the stored value is discarded when the component unmounts.
Compatibility and accessibility
The hook is SSR-safe and uses no browser APIs. If previous and current values are displayed together, label both states explicitly.