0

so I have this code in material UI react js which is not updating the value properly or so I thought, to explain this further I have this code

import * as React from 'react';
import Tabs from '@mui/material/Tabs';
import Tab from '@mui/material/Tab';

export function Home() {


const [value, setValue] = React.useState('Pending');

  const handleChange = (event, newValue) => {
      setValue(newValue);
      console.log(value);
  };

  return (
    <div>
        <>
        <Tabs
          value={value}
          onChange={handleChange}
          textColor="secondary"
          indicatorColor="secondary"
          aria-label="secondary tabs example"
        >
          <Tab value="Pending" label="Pending" />
          <Tab value="Received" label="Received" />
          <Tab value="Prepared" label="Prepared" />
          <Tab value="Cancelled" label="Cancelled" />
        </Tabs>
        </>
    </div>
  );
}

If I run this code and click on the Tab with the label "Pending" the console.log won't be triggered. if I click again on the Tag with the label "Received" the console.log with displays "Pending" instead of "Received".

This happens all the time I thought when you set the value and console log it should show the latest value you selected.

sample output:

enter image description here

As you can see am currently selected the "Received" Tag but on the display its showing "Pending"

Is this how react js/Material UI behaves or am I just missing something here?

thanks

1
  • 1
    Setting state is asynchronous. Commented Feb 1, 2023 at 17:00

1 Answer 1

1

Like Dave Newton said in the comments, setting the state is asynchronous as mentioned in the React Docs here: https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous

If you want to console.log the value, you can update your handler to log the new value instead

const handleChange = (event, newValue) => {
  setValue(newValue);
  console.log(newValue);
};

Or you can use useEffect outside the handler to always log value when it changes

useEffect(() => {
    console.log(value);
}, [value]);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.