Reputation: 621
I have written a component like below where I use React.useState to control the logic to show the button.
If I click the button, it will reveal a sub-button, which was hidden initially, then, if I click on the sub button, it will reveal some content, but the second operation never gets executed.
Below is the code:
MyButton code:
export default observer(function MyButton() {
...
const [subButtonHidden, setSubButtonHidden] = React.useState<boolean>(true)
...
const onClickSubButton = () => {
if (!subButtonHidden) {
displaySubButtonContent(); // never ever reach here
}
setSubButtonHidden(!subButtonHidden);
}
return (
<Subbutton
...
subButtonHidden={subButtonHidden}
onClickSubButton={onClickSubButton}
/>
);
});
SubButton code:
export default observer(function SubButton(props: ...) {
....
const onClickSubButton = React.useCallback(() => {
props.onClickSubButton();
}, []);
....
return props.subButtonHidden ? null : (<div>...</div>);
}
It turns out that subButtonHidden can be successfully updated as false for the very first click, hence show the sub button, but if I click the sub button, subButtonHidden will be somehow reset to true, if I click on the sub button again, subButtonHidden will still be true, even setSubButtonHidden(false) has been executed, no matter what it just doesn't take the updated values. Why is it behaving like that?
Upvotes: 1
Views: 745
Reputation: 1393
In the Subbutton
, you have wrapped the onClickSubButton
with useCallback
with no dependencies. That means its never changed. and that means props.onClickSubButton
is never changed inside the onClickSubButton
.
So when the first time it is clicked, subButtonHidden
is found as true and is set to false. When you click the second time, since onClickSubButton
is not updated because of useCallback, that means the same props.onClickSubButton
was called in which subButtonHidden
was true(because of closures).
So removing the useCallback
around onClickSubButton
should solve your issue.
Upvotes: 3
Reputation: 246
I think you're just changing it directly that one time. Instead you should
setSubButtonHidden(prev => !prev);
it should change depending on what it is (or was) not just directly changing it that one time from its original.
How to toggle boolean state of react component?
Upvotes: 0