Dimitris Karagiannis
Dimitris Karagiannis

Reputation: 9358

How do react hooks reference values passed to the array of dependencies?

Say I have this component, with the following hook:

function SomeComponent(props) {
useEffect(
    () => {
        //....code
        if (props.propOne === ....) { .... }
        // ...code
        if (props.propTwo === ....) { .... }
    }, 
    [props.propOne]
)

return <Something />

}

The above hook will run

Notice however that the hook callback also makes a reference to pros.propTwo, without actually having it passed to the dependencies array.

While props.propTwo will never factor in whether the hooks gets re-executed, what happens to the value of it that the hook callback references inside its body?

for example

Does the hook reference values based on the closure created on component execution or does React do some voodoo where it only keeps the updated value for values passed to the dependencies array?

From the docs:

The array of dependencies is not passed as arguments to the callback. Conceptually, though, that’s what they represent: every value referenced inside the callback should also appear in the dependencies array.

UPDATE:

After asking the question I fell unto this article, by Dan Abramov:

https://overreacted.io/a-complete-guide-to-useeffect/

I suggest everyone to read it.

Upvotes: 1

Views: 551

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281686

React hooks rely heavily on closures to make use of values. The values that are referenced within the hook will be the values that were present in the closure of useEffect when it was last called.

For instance, in your example if props.propOne is changed and in the subsequent render props.propTwo is changed, the value of props.propTwo inside the useEffect callback will the previous value since useEffect is not executed when props.propTwo changes.

If however, you are updating props.propOne and props.propTwo together, then the value inside useEffect hook will be the updated one.

Considering your case where the props.propOne and props.propTwo are changed together and trigger a render, the value of props.propTwo will be D inside useEffect callback

Upvotes: 2

Related Questions