Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why the variable inside of useEffect "delays" updating its value?

  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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading