UNPKG

haunted

Version:
39 lines (38 loc) 1.07 kB
import { hook, Hook } from "./hook"; /** * @function * @template {*} T * @param {T} [initialState] - Optional initial state * @return {StateTuple<T>} stateTuple - Tuple of current state and state updater function */ const useState = hook(class extends Hook { args; constructor(id, state, initialValue) { super(id, state); this.updater = this.updater.bind(this); if (typeof initialValue === "function") { const initFn = initialValue; initialValue = initFn(); } this.makeArgs(initialValue); } update() { return this.args; } updater(value) { const [previousValue] = this.args; if (typeof value === "function") { const updaterFn = value; value = updaterFn(previousValue); } if (Object.is(previousValue, value)) { return; } this.makeArgs(value); this.state.update(); } makeArgs(value) { this.args = Object.freeze([value, this.updater]); } }); export { useState };