I have an input field which has an OnChange function handler to update valA. However the console does not log the changed value after I call the setState for valA - it is one step lagged behind
How can i get it to log the new input?
function test( props ){
const { valA, setValA } = props
function handleOnChange( e ){
var newValA = e.target.value
setValA(newValA)
console.log(valA)
return( null )
}
return( null )
}
I have an input field which has an OnChange function handler to update valA. However the console does not log the changed value after I call the setState for valA - it is one step lagged behind
How can i get it to log the new input?
function test( props ){
const { valA, setValA } = props
function handleOnChange( e ){
var newValA = e.target.value
setValA(newValA)
console.log(valA)
return( null )
}
return( null )
}
Share
Improve this question
asked Mar 13, 2021 at 9:17
Dudey007Dudey007
1052 silver badges7 bronze badges
3 Answers
Reset to default 3You will need to watch your updated state using useEffect
:
function handleOnChange() { // your logic }
useEffect(() => {
console.log(valA);
}, [valA]);
The code you mentioned will not work as expected but the value will be updated correctly. That is The console.log will be execute before the setValue because of js async behaviour but at the end of OnChangeHandler, the value will be updated as expected. As @AdriSolid mentioned the best way to look at the value updated is by using the useEffect hook and it is not remended to use console.log to view state values as the behaviour will not be as expected because of async behaviour. It is not that the value is a state behind, The value will be updated correctly its just the execution behaviour which makes us think it is a state behind!
Moreover, you can you useRef hook instead of the event object to update the value
Something like this,
const ref = useRef();
const [value, setValue] = useState("");
useEffect(() => console.log(value), [value]);
const OnChangeHandler = () => {
var newValA = ref.current.value
setValue(newValA)
// console.log(value)
return( null )
}
return (
<div className="App">
<input
ref={ref}
value={value}
onChange={ OnChangeHandler }
/>
</div>
);
function A(props){
const [input, setinput] = useState(props.valA);
<Input
value={input}
onChange={(e) => setinput(e.target.value)}
/>
console.log(input);
}