Skip to content

[Bug]: hook-use-state reports when setter is not destructured #3871

Open
@AndrewBoklashko

Description

Is there an existing issue for this?

  • I have searched the existing issues and my issue is unique
  • My issue appears in the command-line and not only in the text editor

Description Overview

Sometimes it's necessary to initialize value but never update it. To get a ref-like behavior with more convinient API.

The following code:

const [eventBus] = useState(() => new EventEmitter());

Produces a warning when react/hook-use-state rule is enabled:
Image

Expected Behavior

I acknowledge that this is kind of controvercial because currently it also protects from forgetting a setter. Thus I suggest this behavior to be configurable. Furthermore, config can be done in 2 ways:

  1. opt-in: add allowMissingSetter - boolean(default false)
  2. opt-out: setterIgnorePattern - RegExp that will allow to opt-out of setter check. This is similar to ESLint's no-unused-vars varsIgnorePattern config.

I prefer solution 2 as it's not only more flexible and consistent but also protects from missing setter. The code above could be rewritten as:

const [eventBus, _] = useState(() => new EventEmitter());

This way it explicitly means: I don't need a setter.

eslint-plugin-react version

7.37.3

eslint version

8.57.0

node version

20

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions