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
- once on the first time the component code gets executed
- every time the value of
props.propOnechanges
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
- During initial component rendering
props.propOne === Aandprops.propTwo === B - The hook gets executed and references values
AandB - During a subsequent rendering
props.propOne === Candprops.propTwo === D - The hook gets re-executed, since
props.propOnechanged. It references valueCfor theprops.propOnebut what does it reference for theprops.propTwovalue?BorD?
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.