In React, useRef is typically used to access DOM element references, but it can also be used to store any mutable value that remains consistent throughout the component's entire lifecycle. Unlike regular variables, objects created with useRef persist across component renders, enabling them to store the latest value.
The following are the basic steps to use useRef to reference the latest value:
jsximport React, { useState, useEffect, useRef } from 'react'; function MyComponent() { const [myState, setMyState] = useState('initial value'); const latestValueRef = useRef(myState); useEffect(() => { // When the state changes, update the ref's current value latestValueRef.current = myState; }, [myState]); // Dependency array includes myState to execute whenever the state changes const someFunction = () => { // Access the ref's latest value using the current property console.log('The latest value is:', latestValueRef.current); }; return ( <div> <p>The state is: {myState}</p> <button onClick={() => setMyState('new value')}> Update State </button> <button onClick={someFunction}> Log Latest Value </button> </div> ); } export default MyComponent;
In this example, we create a ref named latestValueRef and initialize it with the initial value of the component state myState. We then use a useEffect hook to listen for changes to myState, updating latestValueRef.current whenever myState changes. Finally, we access the latest state value within someFunction via latestValueRef.current.
It's important to note that useRef does not trigger component re-renders, so changes to latestValueRef.current do not cause the component to update. This differs from useState, which does cause re-renders when the state is updated.