reasonml / reason-react

Reason bindings for ReactJS

Home Page:https://reasonml.github.io/reason-react/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

RFC: Propose `React.useStateValue`

davesnx opened this issue · comments

I want to re-born this PR #426 but with another approach.

Currently React.useState is a weird API https://github.com/jchavarri/reason-react/blob/6ecf6ee6fdb4412114de9eacba1b3adc517eb387/src/React.re#L116-L121 since expects the initial value to be computed once.

Most codebases I have seen there's a binding that fixes this specific issue. Maybe in a different fashion. I think similarly as @jchavarri where a hook that only holds the value matches 1-to-1 to the JS usage.

Internally at @ahrefs we don't use a binding (and therefore it might be unsafe as @rickyvetter suggest). Instead, we implement useState with a dummy useReducer (but it's not a "zero-cost" binding and is exactly the same implementation as React.js #402)

let useStateValue = initial => {
  useReducer((_ignored, newState) => newState, initial);
};

With the interface:

let useStateValue: 'state => ('state, 'state => unit)

I'm opening this PR to gather some feedback if it make sense to add it.