22

I'm currently reducing / removing npm warnings on a React site.

A large number of these warnings are caused by the setState function as seen below, being 'unused'.

const [state, setState] = useState('some state');

Which of the following would be a better way to remove these warnings? Or is there a better way to approach the issue?

1.

const[state] = useState('some state');
const state = 'some state';
Thomas Fox
  • 521
  • 2
  • 5
  • 16

4 Answers4

29

If setState isn't being used at all, then it's a value that never changes so can be a constant (2.). You could probably move it out of the component as well.

ljbc1994
  • 2,044
  • 11
  • 13
  • 5
    you might want to initialize state with some value from props, and then ignore future values of that props, in that case moving the state outside component wouldn't work. – Giorgi Moniava Nov 25 '22 at 10:44
13

If the setter of state is unused, you can avoid it the useState. You can keep the value in a const (in the body of the component), or move outside of the component.

setState is used when it's needed to be aware of the changes in the value stored in state. This way the component knows when to re-render.

Tulio Faria
  • 874
  • 7
  • 16
7

You may be struggling with this (it's how I came to this question):

const [cookies, setCookies] = useCookies(['cookiename']);

Throwing a warning: 'setCookies' is assigned a value but never used [no-unused-vars]

If you would write cookies = useCookies... it would NOT work.

The solution is:

const [cookies,] = useCookies(['cookiename']);
James Stone
  • 487
  • 7
  • 16
2

I also encountered this need. In addition to other suggestions, useRef could be used

For details: https://reactjs.org/docs/hooks-faq.html#is-there-something-like-instance-variables

sinan
  • 570
  • 5
  • 24