kripod / kripod/react-hooks

Add `useEvictingQueue` middleware for keeping track of last N array state items

Open
#35 0 comments 0 reactions 1 assignee Claimed by @kripod View on GitHub
enhancement
Dominant language
TypeScript
Stars
557
Forks
25
PR merge metrics
No merged PRs in 30d

Description

## Motivation

Arrays used as state variables may have a desired length limit. The [EvictingQueue](https://stackoverflow.com/a/15156403) data structure was just made with this purpose in mind. Encapsulating it in a hook as a middleware would allow its usage with any kind of state-returning functions (e.g. `useState` or even `useLocalStorage`).

## Basic example

```ts
function Example() {
const chatMessages = useEvictingQueue(100, useState([]));
}
```

## Details

Basic implementation idea:

```ts
import { useCallback } from 'react';

export default function useEvictingQueue(
maxLength: number,
[value, setValue]: [T[], React.Dispatch>],
) {
const newSetValue = useCallback(
(update: React.SetStateAction) => {
setValue(prevValue => {
const nextValue =
typeof update === 'function' ? update(prevValue) : update;
return nextValue.length > maxLength
? nextValue.slice(nextValue.length - maxLength)
: nextValue;
});
},
[maxLength, setValue],
);

return [value, newSetValue];
}
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.