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]);
2
  • 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 Commented Feb 5, 2020 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. Commented Feb 6, 2020 at 18:48

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.