0

A rule of thumb while using React Hooks is always to call the hooks from the top-level components and not from loops, nested functions, or conditionals. Then how can I conditionally update the state variables using React Hooks (I believe class components support conditional updates to the state variables)?

2
  • 1
    Can you provide an example of what you're trying to do? Commented Jun 17, 2022 at 22:40
  • Let's say that I am having a counter that increments when a button is clicked but the increments should be done only for even-numbered clicks. In this case, I might have two state variables - one which updates every time the button is clicked, another which is displayed on the screen and will update only when the value of the former is even. Commented Jun 20, 2022 at 19:23

1 Answer 1

2

A hook call is different from calling a state setter.

A hook call is a call to a function that starts with use, such as:

const [someState, setSomeState] = useState();

The above may only be called at the top level of a component.

But the state setter may be called from anywhere. You're completely free to do

const [someState, setSomeState] = useState();
if (someCondition) {
  setSomeState('something else');
}

(or to call setSomeState inside a loop)

Although, it would often be more appropriate to put the condition in an effect callback, which will usually produce the same result, but call the state setter less frequently (and thereby reduce the number of unnecessary re-renders, and also reduce the chance of an infinite re-render bug).

const [someState, setSomeState] = useState();
// this will be executed only when someCondition value is updated
useEffect(() => {
  if (someCondition) {
    setSomeState('something else');
  }
}, [someCondition]);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.