Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to avoid "setState never used" when using useContext hook

I know that if you have something like this…

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

and you are getting the warning for setState is never used, you should simply not useState, and instead, a normal variable.

My question is, what if this is useContext instead of useState as shown below? I have this structure for other components but some components do not need to setState for this context. How can I handle this warning? Is eslint my only option here?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const [state, setState] = useContext(myContext);

I have another component that uses the setState but not the state. How would I handle this?

>Solution :

Simply don’t destructure it if you are not going to use it

const [state] = useContext(myContext);

your useContext (and useState) is returning an array. You just restructure the things which are in these posions

const useState = () => ["hi", "mom"];

const [position_0, position_1] = useState();


console.log(postition_0) // "hi"
console.log(postition_1) // "mom"

If you like to skip a variable you could use a throwaway variable like:

const [, position_1] = useState();

More detail in this post

If you are in control of the context however my personal preferred option would be to return an object instead of an array.

const context = () => {
 ...your context here...

 return {
   state,
   setState,
   ...even more...
 }
)

This way you could simply destructure only the things you need:

const { state } = useContext(context); // just state
const { setState } = useContext(context); // just setState
const { state, setState } = useContext(context); // both
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading