I have a problem with the ToggleButtonGroup component of the material-ui library, precisely in the onChange handler. At the beginning my code was more complex, I eliminated the problems one by one until I got this piece of code. But I can't understand the behavior of this code.
export default function ToggleButtons() {
// setting local state
const [values, setValues] = useState(()=>[]);
// toggle buttons handler
const onChangeHandler =(event: any,newValues: string[]) => {
setValues(newValues);
console.log('newValues',newValues);
console.log('state values',values);
};
return (
<ToggleButtonGroup
value={values}
onChange={onChangeHandler}
>
<ToggleButton value='first' >first</ToggleButton>
<ToggleButton value='second' >second</ToggleButton>
<ToggleButton value='third' >third</ToggleButton>
</ToggleButtonGroup>
);
}
Visually everything is perfect. But inside there is something that intrigues me.
It seems that the local state is always delayed. Did I write something wrong? If not then where is the problem?
React updates state asynchronously, so your console.log is printing stale data.
If you use React dev tools to see your state, it's working correctly: