Description
In React, there is a very common issue of needing the most up-to-date version of state from inside a useEffect
, timeout, callback, asynchronous function, etc. It seems the easiest solution is to use a ref, as encouraged by React's own documentation here:
If you intentionally want to read the latest state from some asynchronous callback, you could keep it in a ref, mutate it, and read from it.
Typically, the pattern I use for this is as follows:
const [value, setValue] = useState('some-initial-value');
const valueRef = useRef(value);
valueRef.current = value;
This ensure that on every render we update the ref to contain the latest version of the value
state. This works fine, but it's messy - 3 lines of code instead of 1 for every state we need the latest version of. For components with a lot of useState
calls this gets really ugly really fast for something that's remarkably simple and doesn't affect performance.
My feature request is this: can we just get a ref that points back to the most recent value of state as part of the useState
call? I'd love to be able to do this:
const [value, setValue, valueRef] = useState('some-initial-value');
And then just reference valueRef.current
from within effects, timeouts, intervals, event listener functions, etc. The amount of times I have to use the messy ref workaround is frustrating, and this looks like something React would be able to do so easily just by sticking the latest value in the ref on every render. People could then use it if they want it or continue to call useState() as normal otherwise.
Would certainly clean up my company's codebase markedly. Are there any potential downsides to providing this optional ref that I am missing?