0

when i set state inside function it does not works correctly. i set my state to opposite but it's not change on second console. but console 3 true.

Why it does not return true on second console?

const [checked, setChecked] = useState<any>(false);

function handleSwitchChange() {
    console.log('1. console', checked) ======> return false
    setChecked(!checked);
    console.log("2. console", checked) ======> return false
  }
  console.log("3. console", checked) =====> return true

  <SwitchButton checked={checked} onChange={handleSwitchChange} />
ryouv
  • 25
  • 1
  • 5

1 Answers1

1

useState hook is linked with its related setState hook. This hook is called asynchronously. It means you can't get the changes immediately after this hook is called. There may be many many other functions being called behind the curtain. Henceforth, you are not immediately getting the updated value. in order to check its changes properly you may use the useEffect hook that will be trigger whenever the trigger parameter is updated.

const handleSwitchChange = () => {
   setChecked(!checked);
 };
useEffect(() => {
   console.log(checked);
}, [checked]);
Muhammad Atif Akram
  • 1,204
  • 1
  • 4
  • 12