2 ms·
One thing that I don't understand: why design useEffect api with dependencies array which does not get passed in the function? If you ask me, I'd design it the
by vbezhenar 4y ago
One thing that I don't understand: why design useEffect api with dependencies array which does not get passed in the function?
If you ask me, I'd design it the following way:
useEffect(f, {a, b, c});
...
function f({a, b, c}) {
...
}
Function f is supposed to be declared outside of render function.
This way you must specify all the dependencies. JavaScript will bite you with undefined value, TypeScript will bite you with compilation error. The drawback is that you'd need to pass setValue functions which are typically immutable, but I don't think that's a bad thing anyway.
- pavlov 4y ago> "Function f is supposed to be declared outside of render function." That's the cinch. To get the benefit of this proposed API design, the effect handler functions must be be outside of the render function so they can't capture any values other than the explicit dependencies. That's not a requirement you can enforce in JavaScript, so it would have to be a linter-level thing. I think it would aesthetically run counter to the prevailing design of React functional components. For better and worse, it feels like the framework designers have made a substantial effort to contain a component inside a single function. With this design, you'd have the component and its effect handlers in the same parent scope even though the handlers are subordinate to the component.
- rk06 4y agoHow would useEffect () access those dependencies? useEffect() them to determine if f() needs to run again or not.