Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
kripod opened this issue Sep 23, 2019 · 0 comments
Assignees
Labels
enhancement New feature or request

Comments

@kripod
Copy link
Owner

kripod commented Sep 23, 2019

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];
}
@kripod kripod added the enhancement New feature or request label Sep 23, 2019
@kripod kripod self-assigned this Sep 23, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant