0

am using useState in my functional component in react ! am just confused about something

[myRoom,setMyRoom] = useState('test1');

when i use for example this function setMyRoom to set my room inside a method , it dose not change the value until the second re-redner

function(){
setMyRoom("test 2")
console.log(myRoom) 
// here i get test1 from the first line but not (test2) !! 
//why don't i get it immediately?
//how can i get it before the re-render?
}

a second question, what is the difference between using setState and using normal JS ? myRoom= 'test2'

Mohamad Alasly
  • 330
  • 3
  • 17
  • 1
    Does this answer your question https://stackoverflow.com/questions/36085726/why-is-setstate-in-reactjs-async-instead-of-sync – keikai Mar 05 '20 at 12:45

2 Answers2

1

The purposes of setMyRoom isn't to change the local variable myRoom. myRoom's probably a const, so that would be impossible to change, and even if it's a let that's not what setting state is trying to do.

Instead, the purpose of calling setState is to tell react that you want the component to rerender. When the component rerenders, it will get a new local variable, with the new value.

how can i get it before the re-render?

It's rare that you need to do that, but if you do, maybe save the value to a variable and use that variable;

const newRoom = "test 2"
setMyRoom(newRoom);
console.log(newRoom);

what is the difference between using setState and using normal JS

setState is the api that react provides for you to tell it that you want the component to rerender. If you don't use it, then you're not telling react to rerender.

Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98
  • i know it's rare , am actually using WebRTC with react so when i press call, i need to save the id of the user that i want to call to a vairable, so i can use it in the signaling methods in all over the file – Mohamad Alasly Mar 05 '20 at 13:30
0

setMyRoom is an async function and you can get the myRoom immediate after calling it.

You can solve your problem:

function(){
const newRoom = "test 2";
setMyRoom(newRoom)
console.log(newRoom) 
}
strdr4605
  • 3,796
  • 2
  • 16
  • 26