dy / unihooks

Universal unreacted hooks
MIT License
21 stars 1 forks source link

Polyfilled standard hooks #11

Closed dy closed 4 years ago

dy commented 4 years ago

useState(init?, deps?)

  1. Normalizes initializer function (some hook providers have it not implemented).
  2. Takes optional deps to reinitialize state.
function MyComponent(props) {
  // sets `currentValue` to `value` whenever passed `props.value` changes.
  let [currentValue, setCurrentValue] = useState(props.value, [props.value])
}

useEffect(fn, deps?)

  1. Guarantees microtask - react/preact unpredictably call as microtask or sync.
  2. No-deps useEffect(fn) is the same as empty-deps useEffect(fn, []).
    1. React's useEffect(fn) is equivalent to queueMicrotask(fn), which is redundant hook (principle 3).
    2. That is compatible with useState(initFn) (principle 2).
    3. Single-run useEffect(fn) is equivalent to useInit(fn)/useMount(fn) − that reduces cognitive load / lib size (principle 1).
  3. Supports async functions.
  4. Ignores non-functional returns.
function MyComponent(props) {
  let [result, setResult] = useState()

  // called once on init
  useEffect(async () => setResult(await load('/data')))

  // ...
}

Arguments against

That's matter of diversity vs unification.

dy commented 4 years ago

Ok, decided. Better split to useState and useEffect