仅针对某些依赖项更新调用useEffect

我想在更新道具时调用方法。

Naturally, I am using useEffect with that prop as a dependency. The problem is that I need to access other variables in this useEffect without triggering the effect when THEY get updated.

例如:

I want to call useEffect when data changes, but NOT when saveTimeout or saveMethod change.

In the same fashion, I want to call saveMethod on dismount, but I can't because it needs to be in the dependency array, therefore calling it at every change of saveMethod.

function SavingComponent({data, apiInfo}){
    [saveTimeout, setSaveTimeout] = useState(null);

    const saveMethod = useCallBack(()=>{
        clearTimeout(saveTimeout);

        // api call to save the data using apiInfo

    }, [data, saveTimeout, apiInfo])

    // Start a timer to save the data 2 seconds after it is changed (not working)
    useEffect(()=>{
        clearTimeout(saveTimeout);
        setSaveTimeout(setTimeout(saveMethod, 2000));
    }, [data, saveTimeout, saveMethod]);

    // Save immediately on dismount only (not working)
    useEffect(()=>{
      return ()=> { saveMethod(); }
    },[saveMethod])

    return (// some rendering)
}

This is an issue I am constantly running into with other cases and have to hack around. Usually using a custom usePrevious method. I would compare the previous value of the prop to the current and return immediately if the prop I am interested in didn't change.

function usePrevious(value) {
    const ref = useRef();
    useEffect(() => {
        ref.current = value;
    });
    return ref.current;
}

What is the proper way to only call useEffect when SOME dependencies get updated?

评论