React useref not updating

The useRef hook in React is commonly used to reference a DOM element or a value that persists across re-renders but does not trigger a re-render when it changes. However, it does not automatically update when its referenced value changes. To understand this better, let’s take a look at an example.

{`
    import React, { useState, useRef } from 'react';
    
    function App() {
      const [count, setCount] = useState(0);
      const ref = useRef(count);
      
      const handleChange = () => {
        setCount(count + 1);
        console.log(ref.current);
      };
      
      return (
        
); } `}

In the above example, we have a simple functional component called App. It uses the useState hook to create a state variable count which is initially set to 0, and a function setCount to update the value of count. We also have a ref created using the useRef hook and initialized with the initial value of count.

Inside the handleChange function, we call setCount to increment the value of count by 1. After that, we log the current value of the ref object to the console using ref.current.

If you run this code and click the “Increment” button multiple times, you will notice that the logged value remains the same, even though count has incremented. This is because the useRef hook does not automatically update when the referenced value changes.

To update the ref when the referenced value changes, you can do it manually inside the handleChange function like this:

{`
    const handleChange = () => {
      setCount(count + 1);
      ref.current = count + 1;
      console.log(ref.current);
    };
  `}

Now, if you click the “Increment” button, you will notice that the logged value correctly updates to the incremented value of count.

It’s important to note that the useRef hook is primarily used for accessing DOM elements and preserving values across re-renders without triggering a re-render. It should not be used as a replacement for state variables or as a way to track their changes. If you need to react to changes in a state variable, use the useEffect hook instead.

+

Same cateogry post

Leave a comment