Skip to content

Instantly share code, notes, and snippets.

@codemile
Last active December 30, 2021 20:14
Show Gist options
  • Save codemile/015863619e97a1ee6ae00d390294c5c1 to your computer and use it in GitHub Desktop.
Save codemile/015863619e97a1ee6ae00d390294c5c1 to your computer and use it in GitHub Desktop.
Hook that records the history of state changes as an Array buffer upto a certain length.
import {useCallback, useState} from 'react';
export const useStateBuffer = <TType extends any>(
size: number,
initialState: TType
) => {
const [values, setState] = useState<Array<TType>>([initialState]);
const setValue = useCallback(
(next: TType) => setState([...values, next].slice(0, size)),
[values]
);
return [values, setValue];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment