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?

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 {
   ...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

Leave a Reply