Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I avoid unused setState functions? Can React useState be created without a setter?

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';
like image 713
Thomas Fox Avatar asked Nov 30 '22 20:11

Thomas Fox


2 Answers

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.

like image 131
ljbc1994 Avatar answered Dec 04 '22 04:12

ljbc1994


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.

like image 25
Tulio Faria Avatar answered Dec 04 '22 05:12

Tulio Faria