If I was setting the value of a state variable by a number but it was not dependent on the prev value, would I need to update based on prev state?
i.e
const [value, setValue] = React.useState<number>(7);
const handleClick = () => {
setValue(30);
}
would I need to handle the prev value in the handle click ? this is not a counter or anything.
CodePudding user response:
If your next state does not depend on the previous state then you don't need to pass a callback. setValue(30)
is perfectly fine.
Though you could setValue(() => 30)
. Or for readability and self-documenting purpose you can define const reset = () => 30;
and then use it in the component setValue(reset)
.
What you should NOT do is setValue(value 30)
.