React Hooks: using state in useEffect without depending on it
https://softwareengineering.stackexchange.com/questions/403948
-
06-03-2021 - |
Question
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]);
No correct solution
Licensed under: CC-BY-SA with attribution
Not affiliated with softwareengineering.stackexchange