Keno
Keno

Reputation: 2098

Can you use the 'setter' from useState inside a condition?

I know that the general principle is to avoid using hooks inside a loop, condition, or nested function however in regards to setting state, is it ok to do something like this?

function myComponent() {
  const [myVar, setMyVar] = useState();
  ...
  const nestedFunction = () => {
    if (condition) {
      setMyVar(value);
    }
  }
}

If not, how can I accomplish this using Hooks?

Upvotes: 0

Views: 1315

Answers (1)

Ryan Cogswell
Ryan Cogswell

Reputation: 80986

Yes, that is completely fine. The setter is not a hook. useState is the only "hook" in your example.

Upvotes: 1

Related Questions