0.0.9 • Published 2 years ago
nohooks v0.0.9
nohooks
Compose reactive hooks without additional libraries.
Installation
$ npm i nohooks --saveHow it works?
The nohooks library provides a single module with several low-level hooks, e.g.
import { createContext, useState } from 'nohooks';
async function main() {
const scope = createContext(() => {
const [value, setValue] = useState(3);
if (value > 0) setValue(value - 1);
console.log(value);
return value;
})();
console.log(scope.result === 3);
await scope.defer();
console.log(scope.result === 0);
}
main();Notice
scope.resultreturns the initial value immediately, after waiting it returns the last computed value.
Using context
Calling createContext(render[, cb]) will return a function later used to compute values.
It also accepts a second argument that is called to set the scope.set method, for triggering updates.
Available hooks
onError(cb)— Capture unhandled exceptions.useMemo(cb[, deps])— Memoized callback result.useEffect(cb[, deps])— Fires a synchronous callback.useRef([defaultValue])— Returns a persistent unique reference.useState([defaultValue])— Returns a value/setter from the any given value.
Notice that no passing
depswill trigger the given callback on every iteration, use[]to fire it once.
Other utilities
clone(obj)— Returns a copy from any given value.equals(a, b)— Returnstrueifaandbare equal.