Eslint-plugin-react: no-unused-state warning when state only use in setState

Created on 30 Aug 2018  路  12Comments  路  Source: yannickcr/eslint-plugin-react

if setState was written like this

setState(state => ({
b: state.a + 1
}))

state.a has not used anywhere, no-unused-state will report error

bug help wanted

Most helpful comment

another more tricky case for this issue is when state key is not called explicitly from a state, but is destructed from setState arguments:

image

All 12 comments

Can you provide the code for the entire component?

demo:

import React, { Component } from 'react';

class Test extends Component {

  state = {
    a: 1,
  };

  // onClick() {
  //   this.setState(state => ({
  //     b: state.a + 1,
  //   }));
  // }
  onClick() {
    this.setState({
      b: this.state.a + 1,
    });
  }

  render() {
    const { b } = this.state;

    return <div b={b} />;
  }

}

export default Test;

the first onClick will report [eslint] Unused state field: 'a' (react/no-unused-state)

@tarol why do you need to use state here? You don't need, hence the error is reasonable.

@mqklin
At first, this is a example.
And, The first onClick will report error, but the second onClick will not report.
What makes this difference? If I need not to use state in the first onClick, I need't it in the second onClick too.

How is it possible? Eslint is a static linter, it doesn't make sense for it when to report error - before or after click. Oh, I see the problem. You mean first onClick that is commented in your code.

another more tricky case for this issue is when state key is not called explicitly from a state, but is destructed from setState arguments:

image

I'm seeing this error now after trying to upgrade from 7.11.1 to 7.12.3. I have a bit of state (call it foo) and the only use of it is to control logic inside a setState function updater:

this.setState(prevState => {
  if (prevState.foo) {
    // perform extra logic
  }

  // return new state
});

The plugin reports that state.foo is never used in the component, which is wrong.

Possibly a similar issue that was reported earlier on: https://github.com/yannickcr/eslint-plugin-react/issues/1697

Started seeing this error recently. We just updated from using eslint-plugin-react v7.11.0 to v7.12.4
We have some code that is the same as @kaiyoma mentioned, using state that is only ever used for logic inside of setState. It seems this code is now recognized as unused-state.

@bjankord - I believe this should be fixed in https://github.com/yannickcr/eslint-plugin-react/pull/2151

I also don't see this issue anymore after upgrading to the latest version (7.13.0). I guess this can be closed now?

Closing, happy to reopen if needed.

Was this page helpful?
0 / 5 - 0 ratings