I have seted the value inside the function using useState, in same function I have accessed the set value but it doesn't give me the updated value. If I access the set value outside function it gives the updated value. why useState have this behavior and how I can get updated value in in same function where I set value?
export default function App() {
const [value, setValue] = useState(1);
const myFunction= ()=>{
setValue(2);
console.log(value) //it gives me 1, but I need 2 as I set in above line
}
//but if I access the value outside myfunction it gives 2
console.log(value) // it gives 2
return(
....
....
)
}
CodePudding user response:
useState
will change the value on the next render, not immediately. If you need to use the value in some other function either listen for value changes with an useEffect, or store the new value in another variable:
export default function App() {
const [value, setValue] = useState(1);
const myFunction= ()=>{
// storing value I think it happens before rerender
const newValue = 2
setValue(newValue)
doOtherStuff(newValue);
console.log(newValue);
}
// or listen for value changes this will be called after rerender
useEffect(()=>{
doOtherStuff(value);
console.log(value);
},[value])
}
CodePudding user response:
When the console.log in your myFunction is called still the value=1
. Even though you've set it before the updated value is not passed to the log. Console.log before the return runs when the setValue is called(rerender) At the time the value=2
.
You can use useRef to get updated values without rerenders. Use State values(variables) only for showing UI changes.
export default function App() {
const value = useRef(1);
const myFunction= ()=>{
value.current = 2;
console.log(value.current)
}
console.log(value.current)
return(
....
....
)
}