1

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?

2
  • 1
    if you need a state right away u usually dont use a state but a variable. const let Commented Nov 21, 2022 at 10:56
  • In your example it is harmless and okay, but usually it is an indicator of bad coding practices if you need to rely on a state value you just set earlier in the same function. Commented Nov 22, 2022 at 11:39

2 Answers 2

2

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

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

4 Comments

There is no way, I can do it inside the CallMe function?
use the second argument in setState. setState(false, () => console.log(state))
not working, showing an error: Warning: State updates from the useState() and useReducer() Hooks don't support the second callback argument. To execute a side effect after rendering, declare it in the component body with useEffect().
then you have to use the useEffect
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.