Run Effect hook only when both dependencies change

前端 未结 3 973
执念已碎
执念已碎 2020-12-29 11:39

I have a React component that fetches data using the useEffect hook like so:

const cache = {key: \"data-fetched-using-key\"}
function Config({ke         


        
3条回答
  •  借酒劲吻你
    2020-12-29 12:15

    You can create this sort of logic with useRef(). Consider the following example and sandbox: https://codesandbox.io/s/react-hooks-useeffect-with-multiple-reqs-6ece5

    const App = () => {
      const [name, setName] = useState();
      const [age, setAge] = useState();
    
      const previousValues = useRef({ name, age });
    
      useEffect(() => {
        if (
          previousValues.current.name !== name &&
          previousValues.current.age !== age
        ) {
          //your logic here
          console.log(name + " " + age);
          console.log(previousValues.current);
    
          //then update the previousValues to be the current values
          previousValues.current = { name, age };
        }
      });
    
      return (
        
    setName(e.target.value)} /> setAge(e.target.value)} />
    ); };

    Workflow:

    1. We create a ref object for the two values we want to keep track of, in this case its a name and age. The ref object is previousValues.
    2. useEffect is defined but we do not provide it any dependencies. Instead, we just have it execute whenever there is a state-change to name or age.
    3. Now inside useEffect we have conditional logic to check whether the previous/initial values of both name and age are different than their corresponding state-values. If they are then good we execute our logic (console.log).
    4. Lastly after executing the logic, update the ref object (previousValues) to the current values (state).

提交回复
热议问题