@dark-engine/core
Version:
The lightweight and powerful UI rendering engine without dependencies and written in TypeScript (Browser, Node.js, Android, iOS, Windows, Linux, macOS)
46 lines (45 loc) • 1.48 kB
JavaScript
import { detectIsFunction, detectIsEqual } from '../utils';
import { useCallback } from '../use-callback';
import { useUpdate } from '../use-update';
import { useMemo } from '../use-memo';
import { $$scope } from '../scope';
function createTools(options) {
const { get, set, reset, next, shouldUpdate: $shouldUpdate } = options;
const tools = () => {
const prevValue = get();
const newValue = detectIsFunction(next) ? next(prevValue) : next;
const shouldUpdate = () => $shouldUpdate(prevValue, newValue);
const setValue = () => set(newValue);
const resetValue = () => reset(prevValue);
return { shouldUpdate, setValue, resetValue };
};
return tools;
}
function useState(initialValue) {
const update = useUpdate();
const scope = useMemo(
() => ({
value: detectIsFunction(initialValue) ? initialValue() : initialValue,
}),
[],
);
const setState = useCallback(next => {
const $scope = $$scope();
const isBatch = $scope.getIsBatch();
const isForce = $scope.getIsForce();
const getTools = createTools({
next,
get: () => scope.value,
set: x => (scope.value = x),
reset: x => (scope.value = x),
shouldUpdate: (p, n) => isBatch || isForce || !detectIsEqual(p, n),
});
update({
getTools,
setupBatch: isBatch ? () => getTools().setValue() : undefined,
});
}, []);
return [scope.value, setState];
}
export { useState };
//# sourceMappingURL=use-state.js.map