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)?
-
1Can you provide an example of what you're trying to do?Nathan– Nathan2022-06-17 22:40:45 +00:00Commented 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.Naveen Udhay– Naveen Udhay2022-06-20 19:23:41 +00:00Commented Jun 20, 2022 at 19:23
1 Answer
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]);