2

I have run into a situation in React where I want to run a function F in a useEffect hook whenever a value V1 from the store changes. F uses another value from the store V2. I only want to run F when V1 changes, but to have access to the latest value of V2. This means I wouldn't want to include V2 in the list of dependencies for the useEffect.

Below is my current solution, but I wonder if there is a more accepted way of achieving this.

const v1 = useSelector(state => state.v1);
const v2 = useSelector(state => state.v2);

const v2_ref = useRef(v2);
useEffect(() => {v2_ref.current = v2}, [v2]);

useEffect(() => {
  v1 ? doSomething(v2_ref.current) : doSomethingElse();
}, [v1]);
  • I think that if you want to have access to the latest value of X you need to use the useRef hook. I don't see other way of doing it – Vencovsky Feb 5 at 18:35
  • I figured, but I thought maybe there was a different pattern/style for achieving this. I ended up creating a useDynamicRef hook for this functionality. – Ace Feb 6 at 18:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.