Home > Enterprise >  How to avoid "setState never used" when using useContext hook
How to avoid "setState never used" when using useContext hook

Time:12-03

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?

CodePudding user response:

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

CodePudding user response:

If you are getting the warning that setState is never used when using the useContext hook, you can simply not destructure setState from the hook and only use the state variable. This will avoid the warning and allow you to access the context state without having to set it.

Here is an example of how you could use this approach to avoid the warning:

const myContext = React.createContext();

function MyComponent() {
  const state = useContext(myContext);

  return (
    <div>
      {/* Use the context state in your component. */}
      <p>{state.someValue}</p>
    </div>
  );
}

In this example, MyComponent only uses the state variable from the useContext hook, so setState is not destructured and the warning is avoided. This allows MyComponent to access the context state without having to set it.

Alternatively, you can use the eslint linting tool to suppress the warning by adding a comment that tells eslint to ignore the unused setState variable. This can be useful if you want to use the useContext hook in a way that uses setState

  • Related