reactjs / reactjs/react.dev

Prefer functional updates version in hooks documentation

Open
#1,967 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
JavaScript
Stars
11.8k
Forks
7.9k
Avg merge
1d 11h
Merged PRs (30d)
11

Description

Currently React hooks documentation at section Updating state is using a counter example for bot hooks and class based components. To recap:

In a class, we need to call this.setState() to update the count state:

  <button onClick={() => this.setState({ count: this.state.count + 1 })}>
    Click me
  </button>

In a function, we already have setCount and count as variables so we don’t need this:

  <button onClick={() => setCount(count + 1)}>
    Click me
  </button>

Although I can understand than this documentation must be simple and this example is really straightforward, isn't this a bad patter? Modifying state with a value based on old state?

The Functional update version is documented few pages after this example.

I'm wondering if:

  • this example must be changed (although is probably the best type of example for state), or
  • a warning box should be added to warn the user this is not the correct way to do.

To be more clear: I know there's nothing wrong with this specific example, but newcomers can quickly try to do something like calling setCount(count + 1) multiple times.

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.

Research direction

Start with the Updating state section in hooks-state.html and compare its counter example with the Functional updates section in hooks-reference.html. Determine whether the example or an explanatory warning best addresses repeated updates based on previous state; done means the documentation clearly guides newcomers without contradicting the existing example.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, react
Domain
documentation
Issue type
Documentation
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.