> React function components are not constructor functions though, so I don't see how those are relevant
I'm giving an example of whats a normal use case of closures. Running a single function once that creates closures that run zero, one, or multiple times is "normal". Running a single function multiple times that creates closures that run one time and get ignored all other calls of the function is not.
> Running a single function multiple times that creates closures that run one time and get ignored all other calls of the function is not.
This exactly describes a leading-edge debounce function, which I was asked in multiple interviews early in my career to implement on a whiteboard. I'll admit that "problems people feel like giving to junior devs" isn't a great method of measuring whether or not something is simple, but I think it is indicative of how widely that sort of thing is expected to be understood. It also exactly describes any sort of request framework where request responses are cached after the first call and the result is returned without a network hit in subsequent calls.
I would typically save the result of calling debounce (once), then call that, rather than calling debounce over and over on the same inline function (hooks style).
My debounce implementation would *not* be trying to catter to some API that looks like this:
constructor() {
// called only once
this.debouncedFn1 = debounce(() => { justCallCodeHere(); moreLines(); })
this.debouncedFn2 = debounce(() => { anotherFunction(); moreLines(); })
}
render() {
// use the created debounced functions
this.debouncedFn1()
this.debouncedFn2()
}
How would you implement the first version without having access to react hooks? Keep in mind that in every call to debounce, the function object you get as an argument is unique because unique closures get created on every call of render().
I hope that illustrates the key weirdness aspect of hooks.
Yes, that's true in this case, but it's not unusual to have something which uniquely identifies a debounced/memoized/cached function though, so that subsequent calls look it up against a registry and avoid repeated computation. In the context of requests, that's usually the URL itself (or some combination of the URL and some parameters). This sort of registry is basically exactly what a component instance serves as is in the context of hooks.
I'm giving an example of whats a normal use case of closures. Running a single function once that creates closures that run zero, one, or multiple times is "normal". Running a single function multiple times that creates closures that run one time and get ignored all other calls of the function is not.