-
Notifications
You must be signed in to change notification settings - Fork 25
Open
Labels
enhancementNew feature or requestNew feature or request
Description
Motivation
Arrays used as state variables may have a desired length limit. The EvictingQueue 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
function Example() {
const chatMessages = useEvictingQueue(100, useState<string[]>([]));
}Details
Basic implementation idea:
import { useCallback } from 'react';
export default function useEvictingQueue<T>(
maxLength: number,
[value, setValue]: [T[], React.Dispatch<React.SetStateAction<T[]>>],
) {
const newSetValue = useCallback(
(update: React.SetStateAction<T[]>) => {
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];
}Metadata
Metadata
Assignees
Labels
enhancementNew feature or requestNew feature or request