Skip to content

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

@kripod

Description

@kripod

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 request

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions