Skip to content
Advertisement

Access React state of function enclosed inside useRef doesn’t update

I’m trying to access React state inside a function enclosed inside of useRef. However, even with a helper function bound to App to access the state, the state never updates inside of the useRef function.

JavaScript
JavaScript

Advertisement

Answer

The argument passed to useRef is only considered when the component mounts. Only at that time is the value assigned to the ref; it won’t update when the component re-renders.

When the component mounts, the count variable that the ref’s function closes over is the initial state value, which is 0. No matter how many times the component re-renders, the ref’s function, if not reassigned, will still close over that original state value.

If you want the ref’s function to result in an up-to-date value, assign it anew each time there’s a re-render.

JavaScript

Though, in React, usually it’d be better to pass the state itself down and use it, rather than a ref – refs are generally for things that you can’t accomplish using the more functional tools provided by React.

Advertisement