React uses renders to track changes made to state. Once the event handler finishes running, React triggers a re-render and that render will have the new state value. You can then simply read the (now updated) state during this render.
Nothing is stopping you from using the value returned from your prompt right away, but you would simply be reading a plain old JS variable during the execution of the handler (while React state on the other hand persists between renders).
If you don't need to get the name
state every time the component renders but only it when name
changes, you can use the useEffect
hook.
Example
export default function FeedbackForm() {
const [name, setName] = useState(null);
console.log(`component rendered, current name is ${name}`);
useEffect(() => {
console.log("effect running...");
if (name === null) {
return;
}
console.log(`name has changed to ${name}`);
alert(`Hello, ${name}!`);
}, [name]);
function handleClick() {
const newName = prompt("what is your name?");
setName(newName);
}
return (
<div>
<button onClick={handleClick}>Greet</button>
<p>Name: {name}</p>
</div>
);
}
https://codesandbox.io/s/react-name-prompt-6qknz6