explain why you may want to return a function from a resource, instead of just returning a value.
Opened this issue · 0 comments
NullVoxPopuli commented
Example:
const Clock = resource(({ on }) => {
const now = cell(Date.now());
const interval = setInterval(() => now.current = Date.now(), 1000);
on.cleanup(() => clearInterval(interval));
return now.current;
})
vs
const Clock = resource(({ on }) => {
const now = cell(Date.now());
const interval = setInterval(() => now.current = Date.now(), 1000);
on.cleanup(() => clearInterval(interval));
return () => now.current;
})
The reason:
- because the tracked data (
.current
), would be immediately consumed in theresource()
body, the whole thing would be torn down when the clock updates (create a new interval each second). By using a function, only the function invalidates, you retain state, and keep the interval.