r/learnjavascript • u/Neat_Living_6765 • Sep 05 '26
Is it common for a function to return another function and call it inside a callback?
const stop = useIntersectionObserver(
ref,
([entry]) => {
if (entry.isIntersecting) {
setLoaded(true);
stop(); // one-shot: stop observing once we've committed to loading
}
},
{ rootMargin: '200px' }, // start loading 200px before it scrolls in
);In the snippet, I noticed that useIntersectionObserver returns a function, which is assigned to the variable stop, and that returned function is then called inside the callback passed to useIntersectionObserver.
Actually, I'm not asking about useIntersectionObserver itself. I just want to ask about the pattern:
Function A returns Function B, and then Function B is called inside Function A's callback.
I've never written a function with that kind of structure before.
How often do you write functions like this?