const [inputValue, setInputValue] = useState("");
const previousInputValue = useRef("");
useEffect(() => {
previousInputValue.current = inputValue;
}, [inputValue]);
return (
<>
<input
type="text"
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
/>
<h2>Current Value: {inputValue}</h2>
<h2>Previous Value: {previousInputValue.current}</h2>
</>
);
}
I am having trouble to understand how previousInputValue.current is able to yield the previous value of inputValue instead of its current one.
The way I am seeing this is, as soon as you type something in input, it updates "inputValue" then re-renders the component, but the change of variable triggers useEffect which, in turn, updates previousInputValue. And here lies my doubt, that "inputvalue" inside useEffect doesn’t get the current value (that was updated during the first re-render)?
>Solution :
And here lies my doubt, that "inputvalue" inside useEffect doesn’t get the current value
Because useRef changes do not affect the React component lifecycle (does not re-render the component). The value of useRef is updated after component re-render and after useEffect call.
input value change ->
component state change ->
component re-renders ->
useEffect is triggered and logs previous, old value ->
useRef value is updated
// ^^^ the value of useRef won't be visible until next re-render