3 ms·
Basically every call of a functional component MyComponent() represents a new scope. When you're working with a hook such as useEffect(), you have to pay attent
by kin 6y ago
Basically every call of a functional component MyComponent() represents a new scope. When you're working with a hook such as useEffect(), you have to pay attention to the dynamic scope so and correctly trigger the useEffect() with the dependency array.
- ng12 6y agoBut everything in that dependency array is from lexical scope, correct? Your hooks execute in the scope of that call to MyComponent().
- kin 6y agoCorrect, but the callback passed to useEffect is only scoped to the call stack triggered by the dependency array. So, this makes the callback passed to useEffect dynamically scoped.
- ng12 6y agoThe callback is always defined it's just not always invoked. Otherwise it's a regular lexical closure like any callback in JavaScript. Maybe I'm not understanding what you mean by dynamic scope.
- kin 6y agoYes, it's just regular lexical closure. I don't think his comment was literal since JS itself is lexically scoped. If you think about how `this` works in JS, it's very similar to dynamic scoping because it matters where the function is called. With hooks and dependency arrays, similar to dynamically scoped languages, it matters where the function is called. Thing is, people rarely write functions and use `this` is in dynamically scoped ways anymore. Remember when you had to explicitly bind function scope everywhere? With ES6 and arrow functions, I don't miss that. Anyway, hooks forces you into that mindset now.