javascriptreactjsreact-hooksfunctional-programming

UseCallback(), which variables to add to the dependency array?


UseCallback(), are function paramaters always added ot the dependency array in default? whereas variables used directly wihtin the function's body should only be added if I am sure they would be updated?

const User = ({}) => { 
 const [state, setState] = useState(1); 
 const randomVariable = 1;
 
 const handle = useCallback((state) => { 
 const User = setState(state + randomVariable) 
 }, [state]); 
 return ( )
})

Solution

  • Any variable (or similar) that your callback function closes over should be in the dependency array, since if they aren't, an old version of the callback function closing over a previous variable (or similar) will be reused, causing bugs.

    So:

    const User = ({}) => { 
        const [state, setState] = useState(); 
        const randomVariable = /*...presumably something here other than just 0...*/;
        
        const handle = useCallback((state) => { 
            const User = setState(state + randomVariable) 
        }, [randomVariable]); 
        return /*...*/;
    });
    

    If state weren't a parameter to the callback and you wanted to use the one the function closes over, it would also need to be in the dependency list, but your function doesn't seem at first glance to need to use the state state member.

    You may find my answer here handy, it goes into more general detail on useCallback.