3

I'm using React useEffect to update a state. Eslint warns I'm making no-shadow error. I think this is related to some eslint or eslint plugin settings because CRA doesn't cause the same error. How to fix it?

function Sample(props) {
  const { flag } = props;
  const [value, setValue] = useState();

  useEffect(() => {
    if (flag) {
      setValue(value => value + 1);
    }
  }, [flag]);
}

Here, setValue(value => value + 1); the value causes no-shadow due to declared at the useState.

Sung.P
  • 373
  • 2
  • 9

1 Answers1

2

eslint is correctly complaining because you've declared a value variable in your useState hook, but then you're re-declaring another variable called value in your useEffect hook.

The simplest fix is to not shadow the variable name by changing the variable in your setValue call -

useEffect(() => {
  if (flag) {
    setValue(prev => prev + 1);
  }
}, [flag]);
gerrod
  • 6,119
  • 6
  • 33
  • 45
  • 1
    Thanks. I also found that removing 'airbnb' option from the extends of eslint can solve the issue. – Sung.P Jan 31 '20 at 01:20
  • @SungwooPark - yep that would probably work too but you're weakening the linter - the warning it's given you is valid and worth changing your code, otherwise it can lead to unintentional errors! – gerrod Jan 31 '20 at 05:06