Frameworkless hooks
npm install nohooks> Compose reactive hooks without additional libraries.
``bash`
$ npm i nohooks --save
The nohooks library provides a single module with several low-level hooks, e.g.
`js
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();
`
Output
3
true
2
1
0
true
> Notice scope.result returns the initial value immediately, after waiting it returns the last computed value.
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.
- 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 deps will trigger the given callback on every iteration, use [] to fire it once.
- clone(obj) — Returns a copy from any given value.equals(a, b)
- — Returns true if a and b` are equal.