adir abargil
adir abargil

Reputation: 5745

what type of variables can i put in the dependency array of all hooks

I have been working with react for quite some time and i still somehow wonder what type of opjects can i put inside the dependecy array of react hooks (doesnt matter what hook is it), how exactly is react comparing single items inside the dependecy array and should i parse large objects like lists or nested js objects?

for example here is a object the i want useCallback to change whenever a list inside it changes:

function App(){
    const [array,setArray] = useState([{first:'jimmy',last:'willow'}]);
    const someCallback = useCalback(()=>{
        window.alert(JSON.stringify(array))
    }, [array]) // here I wonder what should I usually put?  just the array or should I parse it  to string to something like that....

// ... somthing here changes the state
    return array.map(({first,last})=><div onClick={someCallback}>{first} , {last} </div>)
}

Upvotes: 3

Views: 1832

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370729

You can put absolutely anything inside the dependency array, keeping in mind that comparison is performed based on Object.is. If any of the values are different, it's considered a change.

So, the dependency array can contain anything: normal values like strings and booleans, or null, or even functions and anything else you can think of.

In this particular case, since setArray (if you ever change the array) will be called with a new array, the new value in the stateful array variable will be !== to the prior value in that variable, resulting in the useCallback constructing the callback again. So having [array] for the dependency array should be just fine, as long as you're following React rules normally and not mutating state.

Upvotes: 4

Related Questions