how to use useRef to reference latest value

Related searches

People use useRef to save latest value like this code

function MyComponent({ value }) {
  const valueRef = useRef();
  useEffect(() => {
    valueRef.current = value;
  });
}

I know useEffect needs for concurrent mode.

and useEffect is executed in the order of the definition

function MyComponent({ value }) {
  useEffect(() => {
    console.log('log1');
  });
  useEffect(() => {
    console.log('log2');
  });
}
// result is
// log1
// log2

so in the below code, log1 is printed with old value and log2 is printed with new value

function MyComponent({ value }) {
  const valueRef = useRef();
  useEffect(() => {
    console.log('log1', valueRef.current);
  });
  useEffect(() => {
    valueRef.current = value;
  });
  useEffect(() => {
    console.log('log2', valueRef.current);
  });
}

I think it's weird because the value is different according to the position.

What is the right way to use useRef to reference latest value? (FYI I know it's better to use deps than to use useRef)


It really depends on what you mean by latest value, your code does store latest value to valueRef.current.

  const valueRef = useRef();
  useEffect(() => {
    console.log('log1', valueRef.current);
  });
  useEffect(() => {
    valueRef.current = value;
  });
  useEffect(() => {
    console.log('log2', valueRef.current);
  });

If you do want to have a more "stable" value, then you should use setState.

  const valueRef = useRef();
  const [value, setValue] = useState(null);

  useEffect(() => {
    setValue(1)
    console.log('log1', valueRef.current);
  });
  useEffect(() => {
    // value is still 1
    valueRef.current = value;
  });
  useEffect(() => {
    // value is still 1
    console.log('log2', valueRef.current);
  });

IMHO, useRef is a very difficult topic, it was designed for Dom ref initially. But then people find it useful when it comes to decouple the variable from the rendering state/prop. You can't actually say useRef always store the latest value, it actually still store the regular value, except it won't trigger re-render, since the reference to this ref is fixed after initialization (only ref.current is changing).

Storing values with the useRef hook � Emma Goto, Refs in React give us a means of storing mutable values throughout a component's Referencing a DOM element is done via the ref attribute. We do This last section of the article will cover note-worthy tips of using useRef . In the component above, we have created a reference object that can point to a DOM element using the keyword “useRef”, we can then use this object in some input element using the “ref


To get the latest value from all code positions (render, useEffect body, disposal function body), you have to use at least two useRefs.

Here is the code

export const usePrevRef = value => {
    const currentRef = useRef()
    const prevPref = useRef()
    prevPref.current = currentRef.current
    currentRef.current = value
    return prevPref
}

If you use one useRef, and place the ref.current = value update in ③(or⑤), then the value won't be correct if called from ④and⑥(or⑥).

I wrote a blog on this. Please feel free to check.

React: Using Refs with the useRef Hook | by Ross Bulat, The most common use of refs in React is to create references to DOM elements and run imperative Use useRef hook to store values you want to keep an eye on Last but not least, when it stays still we need to make it gray. One React hook I sometimes use is useRef. import React, where I log to the console the value of the DOM reference of the span element that contains the count value:


The idiomatic way is to store some "current" value for the next render and retrieve the current ref value (the previous value). Hooks FAQ: How to get the previous props or state

const prevValueRef = useRef();
useEffect(() => {
  prevValueRef.current = value; // cache current value for next render
});
const prevValue = prevValueRef.current; // get previous value from last render

Running sandbox demo

Use useRef hook to store values you want to keep an eye on , React official documentation (https://reactjs.org/docs/hooks-reference.html# useref) define useRef as: The useRef Hook is a function that returns a mutable ref object It's handy for keeping any mutable value around similar to how you'd Last, Keep in mind that useRef doesn't notify you when its content� One good reference for this is this article as Updating a ref value is a side effect and side effects should be avoided or even dealt inside the useEffect() hook. The main point I'm saying here is: you can use useRef() for storing values but you shouldn't. Again, thanks for sharing some knowledge with us! 🤗


Hooks API Reference – React, Notice how the useRef value was changed. It doesn’t come with a set method like useState . To change the value, we would directly reassign the value stored on the .current property of the useRef .


useRef Hook as mutable ref object., useRef returns an object with a `current` property. This `current` property gets the initial value of the argument passed to useRef hook. Tagged with typescript, react, useref, hooks.


In the above example, we have imported useRef hook from the ‘react’ then we invoked the useRef hook by passing the initial value null.. In input element we defined ref attribute by passing the nameRef so that we can access that input element by using nameRef.current property.