Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React hooks a functional update causes the eslint no-shadow error

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.

like image 983
Sung.P Avatar asked Sep 15 '25 02:09

Sung.P


1 Answers

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]);
like image 118
gerrod Avatar answered Sep 16 '25 17:09

gerrod