Skip to content

usePrevious

It's track the previous value of a variable, with possibility to enable/disable tracking.

Demo

INFO

The component has:

  • counter useState variable.
  • previous variable returned by usePreviousHook, linked to counter value and toggleTracking function.
  • button increment that executes function to update counter value. It executes toggleTracking respectivelly to disable/renable tracking when value to update is 6/12. When value to update is 15 it executes toggleTracking to disable tracking with 15 as last value.
  • button no track that executes toggleTracking to stop tracking.
  • button track that executes toggleTracking to restart tracking.

When increment button set 6 as value, previous value stop tracking with 5 as last value because no value was passed to toggleTracking. Same thing happens when increment set 12 as value, the tracking restart from 12. When increment set 15 as value, last value tracked is _15_because it was passed to toggleTracking as value to disable tracking.

Loading demo…
Show source code
tsx
import { useState } from "react";
import { usePrevious } from "../../../..";

function UsePrevious() {
    const [count, setCount] = useState(0);
    const [previous, toggleTrack] = usePrevious(count);


    return (<>
        <button onClick={() => setCount((count) => {
            const val = count + 1;
            if (val === 6) {
                toggleTrack(false);
            }
            if (val === 12) {
                toggleTrack(true);
            }
            if (val === 15) {
                toggleTrack(false);
            }
            return val;
        })}>
            increment
        </button>
        <button onClick={() => toggleTrack(false)}>
            no track
        </button>
        <button onClick={() => toggleTrack(true)}>
            track
        </button>
        <p>
            Count is {count}
        </p>
        <p>
            Previous is {previous === undefined ? 'undefined' : previous as number}
        </p>
    </>);
}

UsePrevious.displayName = "UsePrevious";

export { UsePrevious };

Types

UsePreviousProps

  • @template T - The type of the value being tracked.

Parameters accepted by usePrevious.

PropertyTypeRequiredDescription
variableTThe value to track. On each render, the hook stores the current value so it can be returned as the "previous" value on the next render.

UsePreviousResult

  • @template T - The type of the tracked value.

Return value of usePrevious.

IndexTypeDescription
[0]T \| undefinedThe value from the previous render. undefined on the first render, before any previous value has been recorded.
[1](enable: boolean) => voidA function that enables or disables tracking. When called with false, the hook stops recording new previous values — the last recorded value is frozen until tracking is re-enabled with true.

Released under the MIT License.