When using useState hooks in React I have a scenario in which I would like to use it like so:
const [count, setCount] = useState(0);
const [page, setPage] = useState(0);
setCount(currentCount => {
if (currentCount > 0) {
setPage(0);
return 0;
}
return currentCount 1;
});
Is it considered bad practice to use them nested like this? If so, are there any documentation on why this would be bad practice?
CodePudding user response:
You are setting the count to undefined
in the outer callback: you are not using the return keyword, and functions which exit without a returned value return undefined
in JavaScript. In the inner invocation of the state setter, you are closing around the value of currentCount
from the outer callback, and creating an expression which evaluates to 1
greater than that value.
This is potentially a bug, for two reasons:
undefined
will cause a problem for any code in your program which relies on anumber
type for the stateState updates may be asynchronous, so it is not guaranteed that the outer callback will finish execution either before or after the inner invocation of the state setter.
Instead this pattern will provide deterministic behavior:
setCount(currentCount => {
const useZero = currentCount > 0;
if (useZero) setPage(0);
return useZero ? 0 : currentCount 1;
});
CodePudding user response:
Try something like this:
const [count, setCount] = useState(0);
const [page, setPage] = useState(0);
useEffect(() => {
if (count > 0) {
setPage(0);
setCount(0);
}
}, [count]);