I'm trying to alert with the text box value. In the below code, It'll alert whatever the value is in the input.
import { useState } from "react";
export default function App() {
const [value, setValue] = useState("");
function handle() {
alert(value);
}
return (
<div className="App">
<h1>Hello App</h1>
<input
type="text"
onChange={(e) => {
setValue(e.target.value);
}}
/>
<button onClick={handle}>Hello</button>
</div>
);
}
But if there is a text value already set from the varialbe, It's not showing the value in the alert box. It's empty. As you can see in the below code. I'm setting a const hello with a string and setting it as value for the input. But it's not showing in the popup.
import { useState } from "react";
export default function App() {
const [value, setValue] = useState("");
function handle() {
alert(value);
}
return (
<div className="App">
<h1>Hello App</h1>
<input
type="text"
onChange={(e) => {
setValue(e.target.value);
}}
value={"hello"}
/>
<button onClick={handle}>Hello</button>
</div>
);
}
The reason why the alert doesn't display the "correct" state value is because on handle() the value has not change "on time".
Try this
import { useState, useCallback } from "react";
export default function App() {
const [value, setValue] = useState("");
const handle = useCallback(() => {
alert(value);
}, [value]);
return (
<div className="App">
<h1>Hello App</h1>
<input
type="text"
value={value}
onChange={(e) => {
setValue(e.target.value);
}}
/>
<button onClick={handle}>Hello</button>
</div>
);
}
Why useCallback()?
As per React docs. This hook memoise its internal values, and will only update them when any of the dependancies changes.
The value inside the handle() function scope is not updated, by wrapping the handle function inside a useCallback hook and attaching the value state as a dependency you ensure that handle always updates its internal scoped values/variables, hope that helps.