File size: 912 Bytes
e7abd9e |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
import { useState, useCallback, useTransition } from 'react';
export const useBatchedState = (initialState, options = {}) => {
const { batchDelay = 0, useTransitions = false } = options;
const [state, setState] = useState(typeof initialState === 'function' ? initialState() : initialState);
const [isPending, startTransition] = useTransition();
const setBatchedState = useCallback((newState) => {
if (useTransitions) {
startTransition(() => {
if (batchDelay > 0) {
setTimeout(() => {
setState(newState);
}, batchDelay);
} else {
setState(newState);
}
});
} else {
if (batchDelay > 0) {
setTimeout(() => {
setState(newState);
}, batchDelay);
} else {
setState(newState);
}
}
}, [batchDelay, useTransitions]);
return [state, setBatchedState, isPending];
}; |