Search code examples
reactjstypescriptmaterial-uionchangereact-functional-component

Why did the onChange handler delay the local state update in the ToggleButtonsGroup mui component?


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.

enter image description here

But please check my console##

  • First button is checked

enter image description here

  • First button is unchecked

enter image description here

  • Second button is checked then the third

enter image description here

It seems that the local state is always delayed. Did I write something wrong? If not then where is the problem?


Solution

  • 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:

    enter image description here

    enter image description here