Sakib Hasan
Sakib Hasan

Reputation: 57

How to change and access reactjs state in a same function?

I'm kinda new to reactjs and I got a situation where I will have to change a state and then I will need to access the new state value in the same function. Please have a look at the code below,

import { useState } from "react";
import "./styles.css";

export default function App() {
  const [state, setState] = useState(true); // default state true

  const CallMe = () => {
    setState(false); // state change to false
    console.log(state); // expecting false but return true
  };

  return (
    <div className="App">
      <button onClick={CallMe}>CallMe</button>
    </div>
  );
}

When I click the button for first time, I get true when I'm expecting false. Is there anyway, I can do it these thing in a same function like above?

Upvotes: 1

Views: 2443

Answers (2)

Majid M.
Majid M.

Reputation: 4954

React states are asynchronous, so in the below line of code the state has not been changed yet:

console.log(state);

You should use useEffect to see changes:

import { useState } from "react";
import "./styles.css";

export default function App() {
  const [state, setState] = useState(true); // default state true

  useEffect(() => {
    console.log(state)
  }, [state])

  const CallMe = () => {
    setState(false); 
  };

  return (
    <div className="App">
      <button onClick={CallMe}>CallMe</button>
    </div>
  );
}

Upvotes: 0

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41387

state is asynchronous. you need to wait till state update. use useEffect

useEffect(() => {
    console.log(state)
}, [state])

Upvotes: 2

Related Questions