Function: useFrecency()
useFrecency<
T>(storageKey,options?):UseFrecencyReturn<T>
Defined in: use-frecency.ts:261
Ranks items by how often and how recently they were used ("frecency"), and remembers it across reloads.
Each item has a score. record adds one to it, and the score halves every half-life (7 days by default), so an item used many times long ago can rank below one used a few times today. Use it to sort command palettes, "recent" menus, search suggestions and shortcuts, where plain "most recent" or "most used" lists feel off.
Only one score and one timestamp are kept per item, so storage stays small, and the oldest and least used items are dropped past maxItems. Because every score decays at the same rate, the order of the items never changes just because time passes; it only changes when something is recorded, removed or cleared.
The scores are kept with usePersistedState, so they survive reloads,
are shared by every hook that uses the same storageKey (also across
tabs), and corrupt or missing storage simply starts empty. Storage can be
replaced with the storage option. Items are identified by their string
form, so 1 and "1" are the same item.
record, remove and clear have a stable identity. rank and score
read the current scores, so they get a new identity whenever the scores
change; call them while rendering, or list them as dependencies of
useMemo/useEffect.
On the server, and when no storage is available, the scores live in memory
only and rank returns the ids in their given order. The stored scores are
read on the first client render, so a list ranked from them can differ from
the server HTML; render it after mounting if you hydrate it.
Type Parameters
T
T extends string | number
The type of the item ids: a string or a number.
Parameters
storageKey
string
The key the scores are stored under.
options?
UseFrecencyOptions = {}
Optional settings.
Returns
The functions to record, rank, read and forget items.
Examples
const commands = [
{ id: "open", label: "Open file" },
{ id: "save", label: "Save file" },
{ id: "close", label: "Close tab" },
];
const { record, rank } = useFrecency<string>("command-palette");
const byId = new Map(commands.map((command) => [command.id, command]));
const sorted = rank(commands.map((command) => command.id));
return (
<ul>
{sorted.map((id) => (
<li key={id}>
<button onClick={() => record(id)}>{byId.get(id)?.label}</button>
</li>
))}
</ul>
);
// Favor what was used recently: scores halve every hour, and only the
// 20 best items are kept for this tab session.
const { record, score } = useFrecency<number>("recent-docs", {
halfLifeMs: 60 * 60 * 1000,
maxItems: 20,
storage: sessionStorage,
});
// Deterministic scores in tests.
let time = 0;
const { record, score } = useFrecency<string>("test", {
now: () => time,
});
For a live, editable example, see the useFrecency docs page.