UNPKG

@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)

43 lines (42 loc) 1.39 kB
import { detectIsFunction, detectIsEqual } from '../utils'; import { useCallback } from '../use-callback'; import { useUpdate } from '../use-update'; import { useMemo } from '../use-memo'; import { $$scope } from '../scope'; import { trueFn } from '../utils'; function createTools(options) { const { get, set, reset, next, shouldUpdate: $shouldUpdate = trueFn } = options; const $scope = $$scope(); const isBatch = $scope.getIsBatch(); const tools = () => { const prevValue = get(); const newValue = detectIsFunction(next) ? next(prevValue) : next; const shouldUpdate = () => isBatch || $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 tools = createTools({ next, get: () => scope.value, set: x => (scope.value = x), reset: x => (scope.value = x), shouldUpdate: (p, n) => !detectIsEqual(p, n), }); update(tools); }, []); return [scope.value, setState]; } export { createTools, useState }; //# sourceMappingURL=use-state.js.map