Home > database >  React Re-Rendering Unexpected Behavior
React Re-Rendering Unexpected Behavior

Time:08-21

Below is code snippet

const MuiSelect = () => {

    const [country , setCountry] = useState('')
    console.log("C1: "   country)
    const handleChange = (event : React.ChangeEvent<HTMLInputElement>) => {
      setCountry(event.target.value as string)
      console.log("C2: "   country);
    }

  return (
    <Box width="250px">
        <TextField label="Select country"
         select 
        value={country} 
        onChange={handleChange}
        fullWidth>
            <MenuItem value="PK">Pakistan</MenuItem>
            <MenuItem value="US">United States</MenuItem>
            <MenuItem value="SA">Saudi Arabia</MenuItem>
            <MenuItem value="IR">Iran</MenuItem>
        </TextField>
    </Box>
  )
}

In C1 I am getting updated value when component render/re-render. But in C2 I am getting old/previous state of the country. I am having difficult time to understand this. Can someone explain?

CodePudding user response:

When setting the state with useState there is no guarantee that it will be set instantly. That's why I think you see the old state in C2, because the state has not been set.

You may use a useEffect to log the updated state name

useEffect(()=>{
   console.log("Updated country", country);
}, [countary])

CodePudding user response:

To use the updated value of state, a component has to re-render. In your case when you are updating the state, first your component complete the handlechange function call and then it updates the state where you see C1 with updated state.

CodePudding user response:

Also, if you need store some mutable value u can use React.createRef(). But ref change will not trigger component re-render.

CodePudding user response:

React doesn't update state immediately. React changes states when re-rendering. In order to perform efficiently, re-rendering occurs just one time lazily when there are a number of states changing in the one event. This is called "batch update" in React.

C1 variable in logs has been already changed after rendering.

So timely, C2(before change in event) - Rerendering - C1(after change)

Here is a good post for you.

  • Related