Home > front end >  How to change and access reactjs state in a same function?
How to change and access reactjs state in a same function?

Time:11-21

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?

CodePudding user response:

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

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

CodePudding user response:

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>
  );
}
  • Related