Add `useEvictingQueue` middleware for keeping track of last N array state items
- 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
Assessment
This issue has not been assessed yet.