Is it essential to use setState? Could useRef work?
import {useRef} from 'react';
const App = () => {
const inputRef = useRef(null);
function handleChange() {
const {name, value} = inputRef.current;
console.log({[name] : value});
}
return (
<div>
<input
onChange={handleChange}
ref={inputRef}
type="text"
id="message"
name="message"
/>
</div>
);
};
export default App;
But assuming your real use case doesn't involve a console.log, it may not matter if setState doesn't update instantly. In the below example We see the new value displayed on the screen near instantly in the h2 tag even if the console.log shows the old value:
import {useState} from 'react';
const App = () => {
const [message, setMessage] = useState('');
const [someState, setSomeState] = useState('');
const handleChange = event => {
const { name, value } = event.target
setMessage(value)
setSomeState({[name]:value})
console.log('value is:', someState);
};
return (
<div>
<input
type="text"
id="message"
name="message"
onChange={handleChange}
value={message}
/>
<h2>{JSON.stringify(someState)}</h2>
</div>
);
};
export default App;
Some more details here.