Skip to content

Prefer functional updates version in hooks documentation #1967

Description

@keul

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions