RFC: Propose `React.useStateValue`

Open
#698 0 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
5/5
Estimated time
Over a week
Newbie friendliness
25/100
Issue type
Feature
Clarity
Needs clarification
Activity status
Stale
Tech stack
react
Domain
frontend

Research direction

Start by reading src/React.re around the existing React.useState binding and review the referenced PR 426 and issue 402. Compare the proposed useStateValue API and its useReducer-based approach, then establish a decided API and acceptance criteria before implementation; the issue currently asks for feedback rather than defining done.

Written by the indexing model from the issue text.

Description

RFC

I want to re-born this PR https://github.com/reasonml/reason-react/pull/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 https://github.com/reasonml/reason-react/issues/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.

Dominant language
Reason
Stars
3.3k
Forks
344
PR merge metrics
No merged PRs in 30d

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from reasonml/reason-react

All issues in reasonml/reason-react

Similar issues

More Web Dev issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.