React useEffect Hook when only one of the effect's deps changes, but not the others

后端 未结 6 658
小蘑菇
小蘑菇 2020-12-13 14:01

I have a functional component using Hooks:

function Component(props) {
  const [ items, setItems ] = useState([]);

  // In a callback Hook to prevent unnece         


        
6条回答
  •  别那么骄傲
    2020-12-13 14:46

    An easy way out is to write a custom hook to help us with that

    // Desired hook
    const useCompare = (val) => {
        const prevVal = usePrevious(val)
        return prevVal !== val
    }
    
    // Helper hook
    const usePrevious = (value) => {
        const ref = useRef();
        useEffect(() => {
          ref.current = value;
        });
        return ref.current;
    }
    

    and then use it in useEffect

    const Component = (props) => {
        const hasItemIdChanged = useCompare(props.itemId);
        useEffect(() => {
            if(hasItemIdChanged) {
             // ...
            }
        }, [items, props.itemId])
    }
    

提交回复
热议问题